需要帮助确定最大和最小用户输入
Need help determining maximum and minimum of user inputs
我正在尝试确定用户提供的每个输入是否是他们所有输入中的 max
或 min
,然后将该输入分配给变量 high
或low
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
.
那是因为你把low
初始化为零,你输入的所有值都比较大,所以永远不会更新。您必须将其分配给可能的最高值 - low = Double.MAX_VALUE;
因此所有其他值都将低于它。
同样,你应该初始化高为
high = Double.MIN_VALUE;
默认情况下,您应该为 low
使用最大值,否则非负输入的条件 lastinput < low
将始终为 false
,而 0 将保留为您的输出。
double low = Double.MAX_VALUE;
问题出在您的以下情况:
if (lastinput < low && lastinput != 0) {
low = lastinput;
}
注意变量low
最初是0。因此,如果您的实际最小值高于 0,那么它不会影响 low
的值,因为它是 0。对此可以有几种逻辑解决方案:
Use a sentinel value : 用 double 的最高可能值初始化 low 以便用户输入始终较低,因此影响 [= 的值13=]
double low = Double.MAX_VALUE;
更改 if 条件:您可以更改 if
条件以说明初始值为 0 的事实。
if (low==0 || (lastinput < low && lastinput != 0)) {
low = lastinput;
}
low
和 high
的值可以由您在循环之前的第一个输入初始化。
我正在尝试确定用户提供的每个输入是否是他们所有输入中的 max
或 min
,然后将该输入分配给变量 high
或low
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
.
那是因为你把low
初始化为零,你输入的所有值都比较大,所以永远不会更新。您必须将其分配给可能的最高值 - low = Double.MAX_VALUE;
因此所有其他值都将低于它。
同样,你应该初始化高为
high = Double.MIN_VALUE;
默认情况下,您应该为 low
使用最大值,否则非负输入的条件 lastinput < low
将始终为 false
,而 0 将保留为您的输出。
double low = Double.MAX_VALUE;
问题出在您的以下情况:
if (lastinput < low && lastinput != 0) {
low = lastinput;
}
注意变量low
最初是0。因此,如果您的实际最小值高于 0,那么它不会影响 low
的值,因为它是 0。对此可以有几种逻辑解决方案:
Use a sentinel value : 用 double 的最高可能值初始化 low 以便用户输入始终较低,因此影响 [= 的值13=]
double low = Double.MAX_VALUE;
更改 if 条件:您可以更改
if
条件以说明初始值为 0 的事实。if (low==0 || (lastinput < low && lastinput != 0)) { low = lastinput; }
low
和 high
的值可以由您在循环之前的第一个输入初始化。