我正在尝试计算数组的平均值,但无法将 int 转换为 double?为什么会发生这种情况?
private void AvgOfArray(){
myWindow.clearOut();
int total = 0;
int[] a = new int[4];
int i = 0;
double avg = 0.0;
while (i < a.length) {
a[i] = 1 + (int) (Math.random() * 10);
myWindow.writeOutLine(a[i]);
total += a[i];
i++;
}
avg = (Double) i;
myWindow.writeOutLine(total/Double.parseDouble(i));
}
最佳答案
计算平均值的正确方法是这样的,
double avg = total / (double) i;
myWindow.writeOutLine(avg);
将 int
装箱为 Double
没有多大意义,尤其是尝试解析它。
关于java - 为什么我不能将整数转换为 double ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36732957/