# 如何获得这些变量的均值？算术函数是什么？

go评论31阅读模式

How do I get the mean of these variables..... What is the arithmetic function?

# 问题

``````如何编写一个方法来计算一些数字的平均值？

public class MyCalculator {

int input1 = 10;
int input2 = 20;
int input3 = 30;
int input4 = 40;
int input5 = 50;

public float average() {
// TODO: 编写Java代码来计算所有输入变量的平均值

return 0;
}
}
``````

How can I write a method to calculate the average of some numbers?

``````public class MyCalculator {

int input1 = 10;
int input2 = 20;
int input3 = 30;
int input4 = 40;
int input5 = 50;

public float average() {
// TODO: write java code to calculate the average for all input variables

return 0;
}
}
``````

# 答案1

``````你可以尝试类似这样的代码，使用了新的 `Stream` 库。

import java.util.stream.*;

class MyCalculator {
public static double average(int[] input) {
return IntStream.of(arr).average().getAsDouble();
}
public static void main(String[] args) {
int[] input = {10, 20, 30, 40, 50};
System.out.println(average(input));
}
}

30.0
``````

You could go for something like this, which uses the new `Stream` library.

``````import java.util.stream.*;

class MyCalculator {
public static double average(int[] input) {
return IntStream.of(arr).average().getAsDouble();
}
public static void main(String[] args) {
int[] input = {10, 20, 30, 40, 50};
System.out.println(average(input));
}
}
``````

Output:

``````30.0
``````

• 本文由 发表于 2020年9月12日 17:52:36
• 转载请务必保留本文链接：https://go.coder-hub.com/63859048.html
• java

go 35

go 45

go 43

go 38