我正在尝试确定用户提供的每个输入是否是他们所有输入中的 max
或 min
,然后将该输入分配给变量 高
或 低
int inputnum = 0;
double sum = 0;
double lastinput = 0;
double high;
double low;
double average;
Scanner input = new Scanner(System.in);
high = 0;
low = 0;
do {
System.out.println("Enter a number. Type 0 to quit.");
lastinput = input.nextDouble(); //reads input
sum += lastinput; //add to sum
if (lastinput != 0) {
inputnum += 1; //counts number of inputs (except 0)
}
if (lastinput > high && lastinput != 0) {
high = lastinput;
}
if (lastinput < low && lastinput != 0) {
low = lastinput;
}
average = (sum / inputnum);
} while (lastinput !=0); //repeat unless user inputs 0
问题是我不能在不给变量赋值(例如 0)的情况下声明变量。例如,如果用户输入 3
、5
和 7
,low
值仍定义为 0
。
最佳答案
问题出在您的以下情况:
if (lastinput < low && lastinput != 0) {
low = lastinput;
}
请注意,变量 low
最初为 0。因此,如果您的实际最小值高于 0,那么它不会影响 low
的值,因为它是 0。对此可以有多种逻辑解决方案:
使用标记值:用最高可能值 double 初始化 low 以便用户输入始终较低,因此影响
low
的值/p>double low = Double.MAX_VALUE;
更改 if 条件:您可以更改
if
条件以说明初始值为 0 的事实。if (low==0 || (lastinput < low && lastinput != 0)) { low = lastinput; }
关于java - 需要帮助确定最大和最小用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46358885/