代码生成 Java 计算列表的累计平均值
时间: 2023-11-01 16:07:38 浏览: 39
以下是 Java 代码生成计算列表的累计平均值:
```java
public static double[] cumulativeAverage(int[] arr) {
double[] res = new double[arr.length];
double cumSum = 0;
for(int i = 0; i < arr.length; i++) {
cumSum += arr[i];
res[i] = cumSum / (i + 1);
}
return res;
}
```
你可以将要计算的整数型数组作为函数的输入,然后返回一个包含所有累计平均值的双精度型数组。
相关问题
代码生成 Java 计算列表的累计平均值,高性能
以下是 Java 代码生成计算列表的累计平均值,使用了高性能的数据结构:
```java
public static double[] cumulativeAverage(int[] arr) {
double[] res = new double[arr.length];
double cumSum = 0;
for(int i = 0; i < arr.length; i++) {
cumSum += arr[i];
res[i] = cumSum / (i + 1);
}
return res;
}
```
这个实现和之前的实现非常类似,但是这里使用了基本类型 `double` 代替了包装类型 `Double`,从而避免了装箱和拆箱的开销。此外,这里也没有使用任何集合类型,因为数组是 Java 中最高效的数据结构之一。
代码生成 计算列表的累计平均值
以下是 Python 代码生成计算列表的累计平均值:
```python
def cumulative_average(lst):
res = []
cum_sum = 0
for i, num in enumerate(lst):
cum_sum += num
res.append(cum_sum / (i + 1))
return res
```
你可以将要计算的列表作为函数的输入,然后返回一个包含所有累计平均值的列表。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)