我正在尝试创建代码来计算最小值和最大值(含)之间的百分比。此代码的输出应为50.0,但我的值为100.0。有什么想法为什么会这样?谢谢! 编辑:代码可以编译,并且我没有除法问题。我对为什么数字不同感到困惑。谢谢!
public class Test {
public static double tempCheck(double[][] temps, double minTemp, double maxTemp) {
int i;
int betweenTemps = 0;
double percentage = 0.0;
int j;
int numVals = 0;
for (i = 0; i < temps.length; i++) {
for (j = 0; j < temps[i].length; j++) {
if (temps[i][j] >= minTemp && temps[i][j] <= maxTemp) {
betweenTemps++;
}
}
numVals++;
}
percentage = (betweenTemps / numVals) * 100;
return percentage;
}
public static void main(String[] args) {
double[][] temps = {
{ 72.0, 78.0, 74.5 },
{ 79.0, 80.0, 71.0 }
};
double minTemp = 70.0;
double maxTemp = 75.0;
System.out.println(tempCheck(temps, minTemp, maxTemp));
}
}
答案 0 :(得分:1)
public class Test {
public static double tempCheck(double[][] temps, double minTemp, double maxTemp) {
int i;
int betweenTemps = 0;
double percentage = 0.0;
int j;
int numVals = 0;
for (i = 0; i < temps.length; i++) {
for (j = 0; j < temps[i].length; j++) {
if (temps[i][j] >= minTemp && temps[i][j] <= maxTemp) {
betweenTemps++;
}
numVals++;
}
}
percentage = ((double) betweenTemps / (double) numVals) * 100.0;
return percentage;
}
public static void main(String[] args) {
double[][] temps = {
{ 72.0, 78.0, 74.5 },
{ 79.0, 80.0, 71.0 }
};
double minTemp = 70.0;
double maxTemp = 75.0;
System.out.println(tempCheck(temps, minTemp, maxTemp));
}
}
您需要在嵌套循环内递增numVals
,并将结果转换为两倍以得到准确的结果。