2012-07-15 29 views
-3

我想和理解以下的幫助:浮置輸出/輸入的問題用C

的代碼:

int main() { 
    int i=23; 
    float f=7.5; 

    printf("%f", i); 
    return 1; 
} 

輸出是0.000000,它是怎麼來的不是7.500000

對於代碼

int main() { 
    int i=23; 
    float f=7.5; 

    printf("%d\n",f); 
    printf("%f",i); 
    return 1; 
} 

輸出是1455115000, 7.500000。爲什麼它沒有編譯錯誤?這是什麼數字1455115000?爲什麼現在7.500000正在印刷?

+0

一般參考;這由'printf'文檔覆蓋。 – bitmask 2012-07-15 18:05:22

回答

1

輸出是0.000000,怎麼會不是7.500000?

因爲%f告訴printf期待一個float,但i不是float。所以你正在調用未定義的行爲

爲什麼它沒有編譯錯誤?

在GCC(也可能是其他編譯器)中,您會收到警告消息。

8

printf調用中不匹配的格式/參數會導致未定義的行爲。如果你打開警告級別,你的編譯器可能會告訴你。例如,clang給出了這樣的警告,你的第一個程序:

example.c:5:10: warning: conversion specifies type 'double' but the argument has 
     type 'int' [-Wformat] 
printf("%f", i); 
     ~^ ~ 
     %d 

和這些的你的第二個:

example.c:5:10: warning: conversion specifies type 'int' but the argument has 
     type 'double' [-Wformat] 
printf("%d\n",f); 
     ~^ ~ 
     %f 
example.c:6:10: warning: conversion specifies type 'double' but the argument has 
     type 'int' [-Wformat] 
printf("%f",i); 
     ~^ ~ 
     %d 

這沒有特殊標誌的都沒有。默認情況下,gcc也會在您的程序中發出警告。例1:

example.c:5: warning: format ‘%f’ expects type ‘double’, but argument 2 has type ‘int’ 

例2:

example.c:5: warning: format ‘%d’ expects type ‘int’, but argument 2 has type ‘double’ 
example.c:6: warning: format ‘%f’ expects type ‘double’, but argument 2 has type ‘int’ 

這兩項編譯器還警告你的printf隱含的聲明,但在我離開這些消息了,因爲他們沒有嚴格把你的問題。

1
  1. 在第一種情況下,你要打印的i的價值,以獲得 值7.5您需要打印f

  2. 在第二種情況下,問題是一個不匹配格式 說明符,並提供給printf()

更多關於2的參數。

要打印float值,它需要與%f格式說明符配對。對於int埃格爾值,這應該是%d。這些都是倒退,這就是爲什麼你看到這種不匹配導致的未定義行爲/輸出的原因。

如果您編譯的程序的警告級別最高,您可能會收到關於這些類型的不匹配/錯誤的警告。

除了

一般的0返回值指示成功的程序終止。 A 非零值值(如1)表示存在問題。可能與您的程序無關,但您可能需要牢記。