[英]Problems with simple use of printf and scanf of double numbers in C
我做了一個非常簡單的程序:
#include <stdio.h>
int main()
{
double x;
printf("Write your number \n");
scanf ("%f", &x);
printf("You've written %f \n", x);
return 0;
}
結果,出現一個奇怪的數字(無論我給x多少):“您已經寫了83096261053132580000000000000000000000000000000000000000000
”
這怎么了 當我將所有數字都更改為“ int”類型時,此程序可以正常工作。
查看在啟用警告的情況下進行編譯時會發生什么:
amb@nimrod-ubuntu:~/so$ gcc -Wall x.c -o x
x.c: In function ‘main’:
x.c:6:9: warning: format ‘%f’ expects argument of type ‘float *’, but argument 2 has type ‘double *’ [-Wformat]
將%f
更改為%lf
, scanf
和printf
函數將正確地double
。
scanf()
說明符錯誤。
使用scanf()
, "%f"
匹配一個float *
,但編碼傳遞了double *
。 使用"%lf"
代替。 代碼的printf()
很好。 請參閱正確格式說明符以在printf中使用double
double x;
printf("Write your number \n");
// scanf ("%f", &x);
scanf ("%lf", &x);
printf("You've written %f \n", x);
一個好的編譯器應該已經警告您@abligh建議的錯誤代碼。 啟用所有警告或考慮使用新的編譯器。
掃描時, &x
必須與正確的scanf()
打印說明符匹配。
"%f"
匹配float *
"%lf"
匹配double *
使用printf()
會更容易。 如果傳遞了float
或double
值(作為可變函數),則float
會提升為double
。
"%f"
和"%lf"
匹配double
"%lf"
%f
用於float
類型。 您應該將%lf
用作double
(長浮點數)。
您需要對scanf和printf使用%lf
。
換句話說,這是:
#include <stdio.h>
int main()
{
double x;
printf("Write your number \n");
scanf ("%lf", &x);
printf("You've written %lf \n", x);
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.