输入N个数到数组中,输出所有大于N个数平均值的数。用java
时间: 2024-10-26 12:17:25 浏览: 16
java 输入一个数字组成的数组(输出该数组的最大值和最小值)
在Java中,你可以创建一个方法来接收用户输入的N个数,并计算它们的平均值,然后找出所有大于平均值的数。以下是一个基本的示例代码:
```java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入数字的数量(N): ");
int n = scanner.nextInt(); // 获取数字的数量
double[] numbers = new double[n];
System.out.println("请输入" + n + "个数:");
for (int i = 0; i < n; i++) {
numbers[i] = scanner.nextDouble(); // 存储用户输入的每个数
}
scanner.close();
// 计算平均值
double average = calculateAverage(numbers);
// 找出大于平均值的数并打印
findAndPrintNumbersGreaterThanAverage(numbers, average);
}
private static double calculateAverage(double[] numbers) {
double sum = 0;
for (double num : numbers) {
sum += num;
}
return sum / numbers.length;
}
private static void findAndPrintNumbersGreaterThanAverage(double[] numbers, double average) {
System.out.println("大于平均值的数有:");
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] > average) {
System.out.print(numbers[i] + " ");
}
}
}
}
阅读全文