`
#include <unistd.h>
int ft_atoi(char *str)
{
int c;
int sign;
int result;
c = 0;
sign = 1;
result = 0;
while ((str[c] >= '\t' && str[c] <= '\r') || str[c] == ' ')
{
c++;
}
while (str[c] == '+' || str[c] == '-')
{
if (str[c] == '-')
sign *= -1;
c++;
}
while (str[c] >= '0' && str[c] <= '9')
{
result = (str[c] - '0') + (result * 10);
c++;
}
return (result * sign);
}
#include <stdio.h>
int main(void)
{
char *s = " ---+--+1234ab567";
printf("%d", ft_atoi(s));
}`
这一行:结果= (strc - '0') +(结果* 10);为什么我们减去零,乘以10?如何将ascii转换为int操作?谢谢..。
发布于 2022-10-29 14:51:43
在回答你的问题之前,一些细节,
在内部,一切都是一个数字,一个字符也不例外。在C中字符是一种提升类型的整数,在C中字符是整数,它被提升类型的整数映射到响应值。
例如,:
大写字母范围
65 => 'A‘到90 => 'Z’
小字母范围
97 => 'a‘到122 => 'z’
数范围
48 => '0‘到57 => '9’
回答您的问题
ASCII字符'0‘从任何ASCII字符中减去,该字符是一个数字(0-9),结果为实际的整数。
,例如
'9'(57) - '0'(48) = 9 (int)
'8'(56) - '0'(48) = 8 (int)记忆字符在C中被提升为整数,读取详细信息以理解这条语句。
此外,ASCII字符'0‘将添加到范围(0-9)范围内的任何整数,结果为ASCII字符。
,例如
9 + '0'(48) = '9'(57) (char)
8 + '0'(48) = '8' (56)(char)发布于 2022-10-29 14:14:42
请参阅ASCII表
“0”的ASCII代码是48 -而不是零。因此,要转换为十进制,您需要减去48。
https://stackoverflow.com/questions/74246019
复制相似问题