我尝试创建atoi函数,并认为我编写了正确的代码,但是当我运行它时,它显示了错误的代码。我正在尝试找出答案,但不知道我做错了什么,请检查代码并提供帮助
我的代码是
#include <stdio.h>
int my_atoi(char *str)
{
int i;
int res;
int sign;
i = 0;
res = 0;
sign = 1;//sign of '-' or '+'
while(str[i] == ' ' || (str[i] >= 9 && str[i] <= 13))
{
i++;
}
if(str[i] == '-')
{
sign = -1;
i++;
}
else if(str[i] == '+')
{
sign = 1;
i++;
}
while(str[i] >= '0' && str[i] <= '9')
{
res = res * 10 + str[i] + '0';
i++;
}
return(res * sign);// to make integer which has value of '-' or '+'
}
int main(void)
{
char str[] = "-2018shiba";
printf("%d\n", my_atoi(str));
return(0);
}
当我运行它时,它显示为-108674
答案 0 :(得分:1)
我在这里看到多个错误。
int foo = str[i] - '0';
在 my_atoi 的最后一个while循环中。索引数字字符串表示形式的值是通过将str [i]的值与数字 base 乘以索引从后面开始的力量来计算的。
例如,让我们看一下“ 1337”:
7*10^0 + 3*10^1 + 3*10^2 + 1*10^3 = 7 + 30 + 300 + 1000 = 1337
如您所见,7的数字索引为0,依此类推。假设您只想忽略 shiba ,您的代码将看起来像 一样:
#include <stdio.h>
#include <string.h>
// Return base^(exponent)
int my_pow(int base, unsigned int exponent)
{
if (exponent == 0) {
return 1;
} else {
int result = base;
for (int i = 1; i < exponent; i++) {
result *= base;
}
return result;
}
}
int my_atoi(char *str, size_t len)
{
int i;
int res;
int sign;
i = 0;
res = 0;
sign = 1;//sign of '-' or '+'
while(str[i] == ' ' || (str[i] >= 9 && str[i] <= 13))
{
i++;
}
if(str[i] == '-')
{
sign = -1;
i++;
}
else if(str[i] == '+')
{
sign = 1;
i++;
}
// Store the index where the number string starts
int j = i-1;
// Find the ending index of the number string
i = len;
while (str[i] < '0' || str[i] > '9') {
i--;
}
int num_end = i;
// Now start at the ending
while(i > j)
{
if (str[i] >= '0' && str[i] <= '9') {
res += my_pow(10, num_end-i) * (str[i] - '0');
} else {
// If a character unequal to a digit is found then skip it
num_end--;
}
i--;
}
return(res * sign);// to make integer which has value of '-' or '+'
}
int main(void)
{
char str[] = "-2018shiba";
printf("%d\n", my_atoi(str, strlen(str)));
char str2[] = "-20X18shiba";
printf("%d\n", my_atoi(str2, strlen(str2)));
return(0);
}