编写一个Java程序,求整型数组的加权平均值
时间: 2023-06-23 19:10:35 浏览: 98
用java编写的一个简单的求平均数的程序
4星 · 用户满意度95%
以下是一个Java程序,可以求整型数组的加权平均值:
```java
public class WeightedAverage {
public static void main(String[] args) {
int[] array = {1, 2, 3};
int[] weights = {4, 5, 6};
double weightedAverage = calculateWeightedAverage(array, weights);
System.out.println("The weighted average is " + weightedAverage);
}
public static double calculateWeightedAverage(int[] array, int[] weights) {
if (array.length != weights.length) {
throw new IllegalArgumentException("The length of the array and weights should be the same");
}
int sum = 0;
int totalWeight = 0;
for (int i = 0; i < array.length; i++) {
sum += array[i] * weights[i];
totalWeight += weights[i];
}
return (double) sum / totalWeight;
}
}
```
该程序接受两个整型数组,一个是要求加权平均值的整型数组,另一个是对应权值的整型数组。程序会先检查两个数组的长度是否相等,若不相等则抛出异常。接着,程序通过一个循环计算加权平均值,并返回结果。
阅读全文