我可以看到这是新程序员的常见问题,但是我没有成功地为我的代码实现任何解决方案.基本上我想将 w 和 v 相除,它们必须保存到一个双变量中.但它打印 [0.0, 0.0, ... , 0.0]
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]
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;
}
这里的这一行 d = w[L]/v[L]; 发生在几个步骤中
This line here d = w[L] /v[L]; takes place over several steps
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];
这会强制 java 在整个过程中使用双精度数学,而不是使用整数数学,然后在最后强制转换为双精度
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
如何检测 32 位 int 上的整数溢出?How can I detect integer overflow on 32 bits int?(如何检测 32 位 int 上的整数溢出?)
return 语句之前的局部变量,这有关系吗?Local variables before return statements, does it matter?(return 语句之前的局部变量,这有关系吗?)
如何将整数转换为整数?How to convert Integer to int?(如何将整数转换为整数?)
如何在给定范围内创建一个随机打乱数字的 intHow do I create an int array with randomly shuffled numbers in a given range(如何在给定范围内创建一个随机打乱数字的 int 数组)
java的行为不一致==Inconsistent behavior on java#39;s ==(java的行为不一致==)
为什么 Java 能够将 0xff000000 存储为 int?Why is Java able to store 0xff000000 as an int?(为什么 Java 能够将 0xff000000 存储为 int?)