我在完成大学给我的练习时遇到了一些困难。 基本上,他们要求我获得一些用户输入,然后计算总和、平均值、最小和最大输入以及范围。
一切正常,直到我尝试获得最小值。我已经彻底查看并亲自尝试过,但由于某种原因我无法让它工作。 这是我的代码:
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);
}
}
尝试将选择更改为小于 smallestInput 像这样:
if(choice < smallestInput){
smallestInput = choice;
}
不是这样:
if(smallestInput < choice){
smallestInput = choice;
}
请注意,0 仍被视为用户的输入:
if (choice < 0) break;
import java.util.*;
class Cmjd{
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
int tot=0;
double avg=0.0;
int min=100,max=0;
for (int i = 0; i<10; i++){
System.out.print("Input Marks "+(i+1)+" : ");
int num = input.nextInt();
tot+=num;
if(min>num){
min=num;
}if(max<num){
max=num;
}
avg=tot/10.0;
}
System.out.print("Total :"+tot);
System.out.print("Max :"+max);
System.out.print("Min :"+min);
System.out.print("Average :"+avg);
}
}
import java.util.Scanner;
class Example{
public static void main(String args[]){
Scanner scanner = new Scanner(System.in);
int total= 0;
int max = 0;
int min = 100;
for (int i=0;i<10;i++) {
System.out.println("Enter mark "+(i+1));
int mark = scanner.nextInt();
total+=mark;
if(min>mark){
min=mark;
}
if(max<mark){
max =mark;
}
}
System.out.println("Total : "+total);
System.out.println("Max : "+max);
System.out.println("Min : "+min);
System.out.println("Average : "+(total/10));
}
}