如何从输入的一组数字中获取最大值和最小值? [英] How do I get the max and min values from a set of numbers entered?
本文介绍了如何从输入的一组数字中获取最大值和最小值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下是我目前的情况:
我不知道如何排除0作为最小数字。赋值要求0为退出号,因此我需要在min字符串中出现0以外的最小数字。有什么想法吗?
I don't know how to exclude 0 as a min number though. The assignment asks for 0 to be the exit number so I need to have the lowest number other than 0 appear in the min string. Any ideas?
int min, max;
Scanner s = new Scanner(System.in);
System.out.print("Enter a Value: ");
int val = s.nextInt();
min = max = val;
while (val != 0) {
System.out.print("Enter a Value: ");
val = s.nextInt();
if (val < min) {
min = val;
}
if (val > max) {
max = val;
}
};
System.out.println("Min: " + min);
System.out.println("Max: " + max);
推荐答案
您只需要跟踪最大值这个:
You just need to keep track of a max value like this:
int maxValue = 0;
然后在迭代数字时,如果maxValue大于,则继续将maxValue设置为下一个值maxValue:
Then as you iterate through the numbers, keep setting the maxValue to the next value if it is greater than the maxValue:
if (value > maxValue) {
maxValue = value;
}
对minValue重复相反的方向。
Repeat in the opposite direction for minValue.
这篇关于如何从输入的一组数字中获取最大值和最小值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文