atof()返回含糊不清的值

我试图使用atof并接收模糊输出将字符数组转换为c中的double。

printf("%lf\n",atof("5")); 

版画

 262144.000000 

我惊呆了。 有人可以解释一下我哪里出错了吗?

确保您已包含atof和printf的标题。 如果没有原型,编译器将假定它们返回int值。 当发生这种情况时,结果是未定义的,因为这与atof的实际返回类型double不匹配。

 #include  #include  

没有原型

 $ 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  #include  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"));