使用for循环编写一个程序,以提示用户输入十二个n的数字,然后显示这些数字的最小值,最大值,总和和平均值。
我不奇怪我将如何使用for循环来实现此目的,我遇到了一些麻烦。
import java.util.Scanner;
public class Loop{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter number 1: ");
double a = scanner.nextDouble();
System.out.println("Enter number 2: ");
double b = scanner.nextDouble();
System.out.println("Enter number 3: ");
double c = scanner.nextDouble();
System.out.println("Enter number 4: ");
double d = scanner.nextDouble();
System.out.println("Enter number 5: ");
double e = scanner.nextDouble();
System.out.println("Enter number 6: ");
double f = scanner.nextDouble();
System.out.println("Enter number 7: ");
double g = scanner.nextDouble();
System.out.println("Enter number 8: ");
double h = scanner.nextDouble();
System.out.println("Enter number 9: ");
double i = scanner.nextDouble();
System.out.println("Enter number 10: ");
double j = scanner.nextDouble();
System.out.println("Enter number 11: ");
double k = scanner.nextDouble();
System.out.println("Enter number 12: ");
double l = scanner.nextDouble();
double minNum = Math.min(a, Math.min(b, Math.min(c, Math.min(d, Math.min(e, Math.min(f, Math.min(g, Math.min(h, Math.min(i , Math.min(j, Math.min(k, l)))))))))));
double maxNum = Math.max(a, Math.max(b, Math.max(c, Math.max(d, Math.max(e, Math.max(f, Math.max(g, Math.max(h, Math.max(i , Math.max(j, Math.max(k, l)))))))))));
double sumNum = (a + b + c + d + e + f + g + h + i + j + k + l);
for(int i = 0; )
}
}
我期望输出与for循环一起使用,但是再次我不明白如何在此方法中使用它。
答案 0 :(得分:1)
这是一种更好的方法,它甚至不需要一次存储所有数字。此处的方法是在输入每个新数字时,在最大和最小输入上保持运行选项卡。另外,我们维护输入的所有数字的总计,以后可以轻松地用来计算平均值。
Scanner scanner = new Scanner(System.in);
double max, min, avg;
double total = 0.0d;
boolean first = true;
int numbers = 12;
for (int i=0; i < numbers; ++i) {
System.out.println("Enter number:");
double d = scanner.nextDouble();
if (first) {
max = d;
min = d;
total = d;
first = false;
}
else {
if (d > max) {
max = d;
}
else if (d < min) {
min = d;
}
total += d;
}
}
avg = total / numbers;
System.out.println("max: " + max + ", min: " + min + ", avg: " + avg);
请注意,更高级的方法可能是执行类似的操作,例如将所有12个数字存储到列表中,然后利用Java 8流API查找最大值,最小值和平均值。但是我怀疑这不是您想要的答案。
答案 1 :(得分:0)
您可以这样做。
Scanner scanner = new Scanner(System.in);
double max = Double.MAX_VALUE, min = Double.MIN_VALUE, total = 0.00d;
int n = 12; // Change this to the number of values needed
for (int i=0; i < n; i++) {
System.out.println("Enter number:");
double d = scanner.nextDouble();
if (d > max) {
max = d;
}
else if (d < min) {
min = d;
}
total += d;
}
Double avg = total / n;
System.out.println("max: " + max + ", min: " + min + ", avg: " + avg);
答案 2 :(得分:-1)
将此Java代码放在主函数中
`Scanner s=new Scanner(System.in);
int t=s.nextInt(); //12
int sum=0;
int min=Integer.MIN_VALUE;
int max=Integer.MAX_VALUE;
for(int i=0;i<t;i++){
int temp=s.nextInt();
if(temp<min)
min=temp;
if(temp>max)
max=temp;
sum+=temp;
}
System.out.println(min +" "+max+" "+sum);`