atof()返回不明确的值

魔鬼

我正在尝试使用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

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章