本文介绍了ATOF()将返回值暧昧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用ATOF和接收暧昧输出到一个字符数组转换为双在C

I am trying to convert a character array into double in c using atof and receiving ambiguous output.

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

打印

262144.000000

我愕然。有人可以解释我我要去哪里错了?

I am stunned. Can somebody explain me where am I going wrong?

推荐答案

请确保您已为ATOF和printf头。如果没有原型,编译器将假定它们返回 INT 值。当发生这种情况的结果是不确定的,因为这不符合的ATOF的实际回报型双

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>

没有原型

$ 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

课:注意你的编译器警告

Lesson: Pay attention to your compiler's warnings.

这篇关于ATOF()将返回值暧昧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-16 17:27