我有几天试图弄清楚如何解决这个问题,但我找不到解决方案。我已经尝试了所有的建议,但我仍然无法弄清楚如何显示最低的数字。
import java.util.Scanner;
public class finalname {
public static void main(String args[]) {
Scanner kb = new Scanner(System.in);
System.out.println("How Many Numbers You Want To Enter: ");
int total = kb.nextInt();
int input = 0;
int sum = 0;
int average=0;
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
while (input < total) {
input++;
System.out.println("Enter " + input + ". Operand: ");
sum += kb.nextInt();
if (min >= sum)
{
min = sum;
}
if (max <= sum)
{
max = sum;
}
average = ( sum ) / ( input);
}
System.out.println("The sum is " + sum + ".");
System.out.println("The avg " + average);
System.out.println("The highest number " + max);
System.out.println("The the lowest number " + min);
}
}
答案 0 :(得分:2)
为什么你+=
sum
?如果您只是想从输入数字中获取最小数字。比改变
sum += kb.nextInt();
要
int n=kb.nextInt();
sum += n;// += will sum your input. It is only need for average.
if(min>n)// To get smallest number from input
答案 1 :(得分:1)
您的代码非常接近工作,但是当您必须比较刚输入的实际数字时,您正在比较sum
。
将数字保存到变量:
int num = kb.nextInt();
sum += num;
if (num < min)
min = num;
if (num > max)
max = num;
循环后,计算平均值
注意:您应该考虑将average
设为float
,以便显示小数结果:
float average = (float) (sum / input);