在这种情况下如何计算平均值?(JAVA)

eanckbw9  于 2023-01-01  发布在  Java
关注(0)|答案(3)|浏览(113)

我有一组数字,命名为age[],我想计算age[]中所有元素的平均值,而不单独计算总和,不是像这样:

int avg2 = (age[0] + age[1] + age[2] + age[3] + age[4] + age[5]) / age.length;

这实在是太长了,想象一下,如果一个有100个元素,那就太难了。

int age[] = { 20, 17, 19, 22, 18, 18 };
String[] names = { "Ahmed", "Sam", "Mandi", "Amine", "John", "Rayan" };
for (int i = 0; i <= 5; i++) {
    if (age[i] >= 20) {
        System.out.println(names[i] + " is " + age[i] + " years old. And he's from Mars!");
    }
    if (age[i] < 20) {
        System.out.println(names[i] + " is " + age[i] + " years old. He is from Wakanda!");
    }
}

int j = 0;
int avg = (age[j] + age[j++]) / age.length;

System.out.println("Their average age is :" + avg + " years.");

int avg2 = (age[0] + age[1] + age[2] + age[3] + age[4] + age[5]) / age.length;

System.out.println("Their correct average age is :" + avg2 + " years.");

我已经查过了,但是没有找到捷径。如果可能的话,请帮我解决这个问题。谢谢。

busg9geu

busg9geu1#

可以在迭代数组时对age的值求和。不要在for循环中硬编码长度。使用一个else而不是两个if。类似于

int age[]= { 20, 17, 19, 22, 18, 18};
String[] names = {"Ahmed", "Sam", "Mandi", "Amine", "John", "Rayan"};
int total = 0;
for (int i = 0; i < age.length; i++) {
    total += age[i];
    if (age[i] >= 20) {
        System.out.println(names[i] +" is "+ age[i] +" years old. And he's from Mars!");
    } else {
        System.out.println(names[i] +" is "+ age[i] +" years old. He is from Wakanda!");
    }
}
double avg = total / (double) age.length;
System.out.println("Their average age is :" + avg + " years.");
z2acfund

z2acfund2#

最简单的方法之一是使用Java Streams API

double avg = Arrays.stream(age).average().getAsDouble();
    • 演示**:
import java.util.*;

public class Main {
    public static void main(String[] args) {
        int age[] = { 20, 17, 19, 22, 18, 18 };
        double avg = Arrays.stream(age).average().getAsDouble();
        System.out.println(avg);
    }
}
    • 输出**:
19.0
4xrmg8kj

4xrmg8kj3#

这里有一种稍微不同的做法。

  • 使用IntStream流式传输数组索引。
  • 使用map打印每个个体的年龄
  • 然后计算平均值
  • 如果存在平均值,则打印它
  • 否则打印通知消息
int ages[] = 
    {20,17,19,22,18,18};
String[] names =
    {"Ahmed","Sam","Mandi","Amine","John","Rayan"};

IntStream.range(0, ages.length).map(i -> {
    int age = ages[i];
    if (age >= 20) {
        System.out.println(names[i] + " is " + age
                + " years old. And he's from Mars!");
    } else {
        System.out.println(names[i] + " is " + age
                + " years old. He is from Wakanda!");
    }
    return age;
}).average().ifPresentOrElse(
        avg -> System.out
                .println("\nTheir average age is: " + avg + " years."),
        () -> System.out.println("No ages were supplied"));

印刷品

Ahmed is 20 years old. And he's from Mars!
Sam is 17 years old. He is from Wakanda!
Mandi is 19 years old. He is from Wakanda!
Amine is 22 years old. And he's from Mars!
John is 18 years old. He is from Wakanda!
Rayan is 18 years old. He is from Wakanda!

Their average age is: 19.0 years.

相关问题