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
教訓: コンパイラの警告に注意してください。
小数点と、小数点の後に少なくとも2つのゼロを使用して、同様の問題を修正しました
printf("%lf\n",atof("5.00"));