C语言 atof() 返回不明确的值



我正在尝试使用 atof 将字符数组转换为 c 中的双精度数组并接收模棱两可的输出。

printf("%lfn",atof("5"));

指纹

262144.000000

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

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

#include <stdio.h>
#include <stdlib.h>

无原型

$ cat test.c
int main(void)
{
    printf("%lfn", 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("%lfn", atof("5"));
    return 0;
}
$ gcc -Wall -o test test.c
$ ./test
5.000000

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

我修复了一个类似的问题,在小数点后至少有一个小数点和至少 2 个零

printf("%lfn",atof("5.00"));

最新更新