用c语言如何编写一个函数来计算数组中所有偶数的平均值?
时间: 2024-10-28 08:11:44 浏览: 110
在C语言中,你可以通过以下步骤编写一个函数来计算数组中所有偶数的平均值:
首先,定义一个名为`average_of_evens`的函数,它接受两个参数:数组的指针和数组的长度。我们假设数组元素是整型的,并且遍历整个数组查找偶数。
```c
#include <stdio.h>
double average_of_evens(int* arr, int size) {
int sum = 0; // 初始化偶数之和为0
int count = 0; // 初始化偶数计数为0
// 遍历数组
for (int i = 0; i < size; i++) {
if (arr[i] % 2 == 0) { // 如果元素是偶数
sum += arr[i]; // 累加到总和
count++; // 增加偶数计数
}
}
// 检查是否找到偶数,防止除以0的情况
if (count == 0) {
return 0; // 如果没有偶数,返回0作为平均值
} else {
return (double) sum / count; // 否则,返回平均值
}
}
// 测试函数
int main() {
int arr[] = {1, 2, 3, 4, 5, 6};
int size = sizeof(arr) / sizeof(arr[0]);
double avg = average_of_evens(arr, size);
printf("Average of even numbers in the array is: %.2f\n", avg);
return 0;
}
```
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.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)