atof()返回含糊不清的值

alD*_*blo 4 c atof

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

printf("%lf\n",atof("5"));
Run Code Online (Sandbox Code Playgroud)

版画

262144.000000
Run Code Online (Sandbox Code Playgroud)

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

Joh*_*ica 12

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

#include <stdio.h>
#include <stdlib.h>
Run Code Online (Sandbox Code Playgroud)

没有原型

$ 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
Run Code Online (Sandbox Code Playgroud)

原型

$ 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
Run Code Online (Sandbox Code Playgroud)

课程:注意编译器的警告.

  • 更一般地说,启用(并注意)编译器警告/错误! (8认同)