2016-09-23 42 views
0

我正在努力學習更細粒度的計算,並且已經開始同時研究Linux和C.直到現在纔開始順利航行。來自初學C程序的意外行爲

我在內核3.16.0-38-generic上運行Linux Mint 17,並使用Code :: Blocks 13.12作爲我的IDE。

以下貼圖是我使用數據類型,變量和printf()的練習代碼,以及我在vt中看到的相關輸出 - 我看到的奇怪之處在於,在使用浮點數據類型對小數位進行實驗時,似乎在第5小時和最後小數點後第四位跳過了數值。

我濫用調用變量的過程,我是否在代碼中缺少一個錯誤,或者這是CodeBlocks中的錯誤?而且 - 我不知道爲什麼在預覽我的代碼片斷完全一起搗碎,所以被編譯我爲窮人可讀性

代碼道歉,並執行:編譯

/* Prints a message on the screen */ 

#include <stdio.h> 
echar a1 = 'a'; 
int i1 = 1; 

float f1 = 0.123456; 

int main() 

{ 
    printf("Testing %c la%sof characters using variables \n", a1, "rge string "); 
    printf("This line has the values %d and %f.\n", i1, f1); 
    printf("%f can also be displayed as %.5f or %.4f or %.3f or %.2f or %.1f or %.0f \n", 
     f1, f1, f1, f1, f1, f1, f1); 
    printf("Which is an integer . . ."); 
    return 0; 
} 

輸出和執行代碼

Testing a large string of characters using variables 
This line has the values 1 and 0.123456. 
0.123456 can also be displayed as 0.12346 or 0.1235 or 0.123 or 0.12 or 0.1 or 0 
Which is an integer . . . 
Process returned 0 (0x0) execution time : 0.002 s 
Press ENTER to continue.

感謝您提供任何幫助。我正在學習C編程絕對初學者 - 格雷格佩裏

+6

這是四捨五入顯示的最後一位數字,不會跳過前面的數字 –

+1

使用不同的數字,例如0.314159 - 行爲會更清晰。 –

回答

3

正如在評論中提到的,最後一位數字被四捨五入。

如果你有這樣的:

float f1 = 0.777777; 

輸出會是這樣:

This line has the values 1 and 0.777777. 
0.777777 can also be displayed as 0.77778 or 0.7778 or 0.778 or 0.78 or 0.8 or 1 

同樣,如果你有這樣的:

float f1 = 0.999888; 

你會得到這樣的:

This line has the values 1 and 0.999888. 
0.999888 can also be displayed as 0.99989 or 0.9999 or 1.000 or 1.00 or 1.0 or 1 
+0

非常感謝大家的迴應。這看起來很明顯,我的學習材料沒有提到當你放置一個地方值時,C輪轉浮點值。 – user29448

+0

@ user29448很高興能幫到你。如果您覺得它有用,請隨時[接受此答案](http://stackoverflow.com/help/accepted-answer)。 – dbush