在java中将两个整数除以双精度

新手上路,请多包涵

我可以看到这是新程序员的常见问题,但是我没有成功地为我的代码实现任何解决方案。基本上我想除以 w 和 v,这必须保存到一个 double 变量中。但它打印 [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;
}

原文由 roarknuppel 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 452
2 个回答

此处的这一行 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

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

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

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

原文由 Richard Tingle 发布,翻译遵循 CC BY-SA 3.0 许可协议

使用如下

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

原文由 stinepike 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题