gpt4 book ai didi

Java 平均水平及以上

转载 作者:行者123 更新时间:2023-12-01 18:24:16 24 4
gpt4 key购买 nike

我正在编写一个程序,您必须找到用户输入的 10 个整数的平均值,然后让程序告诉我用户输入的数字实际上高于平均值,然后实际打印这些数字。我对它告诉我什么高于平均水平以及哪些数字有疑问。相反,在计算平均值之后,它只是在输出中不断给我类似的内容

有 0 个数字高于平均水平这些数字是:0

我做错了什么?

public class Average {
static Scanner keyboard = new Scanner(System.in);
static int sum = 0, aboveAverage;
static double average;

public static void main(String[] args) {
int[] listOfInt = new int[10];// 10 integers MAX

System.out.println("Enter " + listOfInt.length + " integers: ");
for (int count = 0; count < listOfInt.length; count++) {
listOfInt[count] = keyboard.nextInt();
}
for (int count = 0; count < listOfInt.length; count++) {
sum = sum + listOfInt[count];
}
average = sum / listOfInt.length;// sum divided by 10
System.out.println("Average: " + average);

if (aboveAverage > average);

System.out.println("There are " + aboveAverage+ " numbers above the average");
System.out.println("Those numbers are: " + aboveAverage);
}

}

最佳答案

您的if block 以分号终止;你可以像这样修复它

if (aboveAverage > average) { //;
System.out.println("There are "+aboveAverage+" numbers above the average");
System.out.println("Those numbers are: " + aboveAverage);
}

编辑

在检查其余代码时,我认为您确实需要类似的东西(使用 diamond operator <> )

double average = ((double) sum) / listOfInt.length;// sum divided by 10
System.out.printf("Average: %.2f%n", average);
List<Integer> aboveAverage = new ArrayList<>();
for (int v : listOfInt) {
if (v > average) {
aboveAverage.add(v);
}
}
System.out.printf("There are %d numbers above the average%n",
aboveAverage.size());
System.out.printf("Those numbers are: %s%n", aboveAverage);

编辑2

综合起来,

public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int[] listOfInt = new int[10];// 10 integers MAX

System.out.println("Enter " + listOfInt.length + " integers: ");
for (int count = 0; count < listOfInt.length; count++) {
listOfInt[count] = keyboard.nextInt();
}
int sum = 0;
for (int i : listOfInt) {
sum += i;
}
double average = ((double) sum) / listOfInt.length;
System.out.printf("Average: %.2f%n", average);
List<Integer> aboveAverage = new ArrayList<>();
for (int v : listOfInt) {
if (v > average) {
aboveAverage.add(v);
}
}
System.out.printf("There are %d numbers above the average%n",
aboveAverage.size());
System.out.printf("Those numbers are: %s%n", aboveAverage);
}

关于Java 平均水平及以上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26766273/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com