我正在尝试使用 atof 将字符数组转换为 c 中的 double 并接收模棱两可的输出。
printf("%lf\n",atof("5"));
印刷
262144.000000
我惊呆了。有人可以解释我哪里出错了吗?
确保您已包含 atof 和 printf 的标题。如果没有原型,编译器将假定它们返回int
值。发生这种情况时,结果是未定义的,因为这与 atof 的实际返回类型不匹配double
。
#include <stdio.h>
#include <stdlib.h>
$ cat test.c
int main(void)
{
printf("%lf\n", atof("5"));
return 0;
}
$ gcc -Wall -o test test.c
test.c: In function ‘main’:
test.c:3:5: warning: implicit declaration of function ‘printf’ [-Wimplicit-function-declaration]
test.c:3:5: warning: incompatible implicit declaration of built-in function ‘printf’ [enabled by default]
test.c:3:5: warning: implicit declaration of function ‘atof’ [-Wimplicit-function-declaration]
test.c:3:5: warning: format ‘%lf’ expects argument of type ‘double’, but argument 2 has type ‘int’ [-Wformat]
$ ./test
0.000000
$ cat test.c
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
printf("%lf\n", atof("5"));
return 0;
}
$ gcc -Wall -o test test.c
$ ./test
5.000000
教训:注意编译器的警告。
我通过有一个小数点和小数点后至少 2 个零来解决类似的问题
printf("%lf\n",atof("5.00"));