2017-06-04 71 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);