問題描述
我可以看到這是新程序員的常見問題,但是我沒有成功地為我的代碼實現任何解決方案.基本上我想將 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模板網!