2017-06-04 69 views
-1

這個簡單的代碼有點問題。C中的雙值錯誤

我已經嘗試過不同類型的鑄件,但是我在這裏沒有任何問題。如果有人告訴我爲什麼總是打印0.0000000或類似的原因,我會提前感到遺憾和感謝。

#include<stdio.h> 
main() 
{ 
    double num1,num5; 
    printf ("Hello user\n"); 
    printf ("Let the thickness of black and white brick are same and the value 
      is 2m\nAnd the gap between them is 1m\n"); 
    printf ("\nEnter the length of the road:\n"); 
    scanf ("%lf",&num1); 
    num5 = ((2/5)*num1); 
    printf ("%lf",num5); 
    return 0; 
} 
+0

重複與https://stackoverflow.com/questions/40443602/c-double-not-working-as-expect/40443639# 40443639和https://stackoverflow.com/questions/16221776/why-dividing-two-integers-doesnt-get-a-float –

+0

[分隔1/n總是返回0.0](https://stackoverflow.com/questions/13331054/divide-1-n-always-returns-0-0) –

回答

1

在整數數學中,2/5是0(餘數爲2)。在C中,如何使用結果不會影響結果的計算方式(規則已足夠複雜)。因此,將結果乘以double的事實不會改變2/5(兩個整數的商)的計算方式。

2

(2/5)執行整數計算,結果0。我建議這些方法

num5 = 0.4 * num1; 

num5 = 2 * num1/5; 

第二是潛在更準確的(因爲0.4不能精確地double表示)時num1已經是5的倍數。在第一種情況下,誤差是已經存在的一個。

+1

或'num5 =(2.0/5)* num1;'? – pmg

+0

或'num5 =(2/5.0)* num1;'但實際上它們可能實際上是整數變量。 –

0

2和5是整數,它們不是雙重的。添加小數點將產生正確的結果。

就是這樣。

num5 = ((2.0/5.0)* num1); 

num5 = ((2.0/5)* num1); 

num5 = ((2/5.0)* num1);