我在完成大学时的练习时遇到了一些麻烦。 基本上他们要求我获得一些用户输入,然后计算总和,平均,最小和最大输入以及范围。
一切正常,直到我尝试获得最小值。我已经仔细观察并亲自尝试过,但由于某些原因我无法让它工作。 这是我的代码:
import java.util.Scanner;
public class IntSequence {
public static void main ( String arg[]){
Scanner input = new Scanner(System.in);
int sum = 0;
double avg = 0;
int choice = 0;
int i = 1;
int smallestInput = Integer.MAX_VALUE;
int largestInput = Integer.MIN_VALUE;
int range = 0;
System.out.println("Please enter an integer: ");
for(; i <= 1000; i++){
choice = input.nextInt();
if (choice <= 0)
break;
sum = sum + choice;
avg = sum / i;
if(choice > largestInput){
largestInput = choice;
}
if(smallestInput < choice){
smallestInput = choice;
}
}
System.out.println("The sum of all integers is " + sum);
System.out.println("The average of the input integers is " + avg);
System.out.println("The largest input is: " + largestInput);
System.out.println("The smallest input is: " + smallestInput);
}
}
答案 0 :(得分:1)
尝试将更改选择小于minimalInput 像这样:
if(choice < smallestInput){
smallestInput = choice;
}
不是这样:
if(smallestInput < choice){
smallestInput = choice;
}
请注意0仍被用户输入:
if (choice < 0) break;