簡體   English   中英

為什么printf打印錯誤的值?

[英]Why does printf print wrong values?

為什么在使用printf("%f\\n", myNumber)打印一個int時為什么得到錯誤的值?

我不明白為什么它在%d可以正常打印,但在%f卻不能正常打印。 它不應該只是添加額外的零嗎?

int a = 1;
int b = 10;
int c = 100;
int d = 1000;
int e = 10000;

printf("%d %d %d %d %d\n", a, b, c, d, e);   //prints fine
printf("%f %f %f %f %f\n", a, b, c, d, e);   //prints weird stuff

當然,它會打印“怪異”的東西。 您正在傳遞int ,但是告訴printf您已傳遞float 由於這兩種數據類型具有不同且不兼容的內部表示形式,因此您將獲得“亂碼”。

當您將變量傳遞給變量函數如printf ,沒有“自動強制轉換”,這些值將按其實際的數據類型傳遞給該函數(或在某些情況下升級為更大的兼容類型)。

您所做的工作與此類似:

union {
    int n;
    float f;
} x;

x.n = 10;

printf("%f\n", x.f); /* pass in the binary representation for 10, 
                        but treat that same bit pattern as a float, 
                        even though they are incompatible */

如果要將它們打印為浮點型,可以在將它們傳遞給printf函數之前將它們強制轉換為浮點型。

printf("%f %f %f %f %f\n", (float)a, (float)b, (float)c, (float)d, (float)e);

a,b,c,d和e不是浮點數。 printf()將它們解釋為浮點數,這會將奇怪的東西打印到屏幕上。

printf()使用不正確的格式說明符會調用Undefined Behaviour

例如:

 int n=1;
 printf("%f", n); //UB

 float x=1.2f;
 printf("%d", x); //UB

 double y=12.34;
 printf("%lf",y); //UB 

注意: printf() double格式說明符為%f

問題是...在printf內部。 發生以下情況

if ("%f") {
 float *p = (float*) &a;
 output *p;  //err because binary representation is different for float and int
}

printf和變量參數的工作方式是字符串中的格式說明符,例如“%f%f”,它告訴printf類型以及參數的大小。 通過為參數指定錯誤的類型,會引起混淆。

在stdarg.h中查看用於處理變量參數的宏

對於“普通”(指定了所有類型的非variadac函數),編譯器將在需要時將整數類型轉換為浮點類型。

對於variadac參數則不會發生這種情況,這些參數始終按 “原樣”傳遞。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM