21

我可以看到这是新程序员的常见问题,但是我没有成功地为我的代码实现任何解决方案。基本上我想将 w 和 v 相除,它们必须保存到一个双变量中。但它打印 [0.0, 0.0, ... , 0.0]

public static double density(int[] w, int[] v){
double d = 0;
    for(L = 0; L < w.length; L++){
        d = w[L]  /v[L];
    }
    return d;
}
4

3 回答 3

36

这里的这条线d = w[L] /v[L];发生在几个步骤中

d = (int)w[L]  / (int)v[L]
d=(int)(w[L]/v[L])            //the integer result is calculated
d=(double)(int)(w[L]/v[L])    //the integer result is cast to double

换句话说,在你转换为 double 之前精度已经消失了,你需要先转换为 double,所以

d = ((double)w[L])  / (int)v[L];

这会迫使 java 在整个过程中使用双精度数学,而不是使用整数数学,然后在最后强制转换为双精度

于 2013-09-30T09:20:19.140 回答
5

使用如下

    d = (double) w[L]  /v[L];
于 2013-09-30T09:19:36.880 回答
3

实际上w[L]/v[L],这里两者都是整数。在除法运算中,它失去了精度并被截断为integer值。然后将截断integer的转换为double.

解决方案是将操作数或除数或两者都转换为双精度数。然后除法运算将产生一个双倍。

d = w[L]/(double)v[L];
于 2013-09-30T09:19:02.500 回答