我写的代码如下:
#include<stdio.h>
#include<math.h>
#include<string.h>
int strToint(char []);
int main()
{
char str[20];
printf("Enter the string-");
gets(str);
printf("\nthe integer is %d ",strToint(str));
return 0;
}
int strToint(char str[])
{
int i,a,sum=0,k,j;
a=strlen(str);
for(i=0;i<a;i++)
{
k=str[i]-'0';
j=pow(10,a-i-1);
sum+=k*j;
}
return sum;
}
如果我输入 567,我会得到 562,但我不明白为什么。我感觉这可能和pow函数有关。
感谢您的帮助。谢谢!
最佳答案
pow()
是一个浮点函数,其行为因系统而异。标准对其准确性没有任何要求。您的返回值似乎没有达到您要求的准确度。
您不需要实现将文本转换为整数的函数,因为标准库包含执行此操作的函数。一个显而易见的选择是 sscanf
。
但如果你必须实现这样的功能,你应该使用整数运算。任何此类代码都应处理负值,并检查无效输入。例如。当您将 "a"
传递给您的函数时会发生什么?
关于c - 将字符串转换为整数的程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26089023/