英文:
Why is the output for this code incorrect?
问题
我正在尝试创建一个计算在最小值和最大值之间数值百分比的代码(包括最小值和最大值)。该代码的输出应该是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));
}
}
英文:
I'm trying to create code that calculates the percentage of values between a min and max value (inclusive). The output for this code should be 50.0, but I'm getting 100.0. Any ideas on why this is happening? Thanks!
Edit: The code compiles, and I'm not having issues with division. I'm confused as to why the numbers are different. Thanks!
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));
}
}
答案1
得分: 1
你需要在嵌套循环中增加numVals
的值,并将结果转换为double
以获得准确的结果。
英文:
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));
}
}
You need to increment numVals
within the nested loop, and cast your result to a double for an accurate result.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论