可能重複:
Possible Loss of Fraction
What is the behavior of integer division in C?Simpliest操作不靈
我是新的C和我有一些麻煩。下面的代碼:
int nr = 3;
float fl = nr/10;
printf("%4.1f\n", fl);
打印0.0
但不0.3
如我所料。有什麼問題?
可能重複:
Possible Loss of Fraction
What is the behavior of integer division in C?Simpliest操作不靈
我是新的C和我有一些麻煩。下面的代碼:
int nr = 3;
float fl = nr/10;
printf("%4.1f\n", fl);
打印0.0
但不0.3
如我所料。有什麼問題?
nr
是一個int,所以你仍然在做整數除法,但分配給一個浮點數。投nr
的浮動,而不是:
float fl = (float) nr/10;
// or divide by a float
float fl = nr/10.0f;
一個int除以數字將是一個整數,它被舍入。你需要投nr
爲浮點第一...
float fl = (float) nr /10;
或者讓編譯器知道你想要的浮動通過使分母的浮動以及
float fl = nr /10.0f;
截斷是正確的詞:-P – sidyll 2011-06-07 14:38:00
截斷可能是正確的詞,但對於一個新手我認爲更常見的措詞會更有幫助。 – 2011-06-07 14:39:12
此:
float fl = nr/10;
做整數運算。你想:
float fl = nr/10.0;
另外,除非你有一些特定的原因不這樣做,最好使用雙精度浮點活動,而不是浮點數。
int nr = 3;
float fl = nr/10; // float = int/int => integer division and then conversion to float
printf("%4.1f\n", fl);
@奧拉維爾:我不認爲一個關於特定C#警告信息的問題確實是由有關C. – geoffspear 2011-06-07 14:38:35
整數除法問題複製這是同一個問題,他將兩個整數並失去精度。這個問題有很好的解釋。 – 2011-06-07 15:02:54