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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19090526/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 14:00:28  来源:igfitidea点击:

Dividing two integers to a double in java

javaintdoubledivide

提问by roarknuppel

I can see this is a common problem for new programmers, however I didn't succeed in implementing any of the solution to my code. Basically I want to divide w and v, which must be saved to a double variable. But it prints [0.0, 0.0, ... , 0.0]

我可以看到这是新程序员的常见问题,但是我没有成功地为我的代码实现任何解决方案。基本上我想划分 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;
}

采纳答案by Richard Tingle

This line here d = w[L] /v[L];takes place over several steps

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

In other words the precision is already gone before you cast to double, you need to cast to double first, so

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

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

This forces java to use double maths the whole way through rather than use integer maths and then cast to double at the end

这会强制 java 在整个过程中使用 double maths 而不是使用 integer maths 然后在最后转换为 double

回答by Subhrajyoti Majumder

Actaully w[L]/v[L]here both are integer, on division operation it loose precision and trucated to integervalue, latter trucated integeris converted to double.

实际上w[L]/v[L]这里两者都是整数,在除法运算中它会降低精度并截断为integer值,后者截断后integer转换为double.

Solution would be convert operand or divisor or both to double, division operaion would produce decimal value.

解决方案是将操作数或除数或两者都转换为双精度,除法运算将产生十进制值。

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

回答by stinepike

use like following

使用如下

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