atof() is returning ambiguous value

筅森魡賤 提交于 2019-12-01 19:59:13

Make sure you have included the headers for both atof and printf. Without prototypes the compiler will assume they return int values. When that happens the results are undefined, since that doesn't match atof's actual return type of double.

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

No prototypes

$ 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

Prototypes

$ 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

Lesson: Pay attention to your compiler's warnings.

Mohamed Hesham

I fixed a similar problem by having a decimal point and at least 2 zeros after the decimal point with

printf("%lf\n",atof("5.00"));
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!