如何利用C语言求数组x中各元素之和的平均值并输出平均值(
时间: 2023-05-28 17:03:42 浏览: 70
Assuming the array x is already declared and initialized with values, the following C code calculates the average of the elements in the array:
```
#include <stdio.h>
int main() {
int x[] = {1, 2, 3, 4, 5};
int sum = 0;
int n = sizeof(x) / sizeof(x[0]); // number of elements in array
float avg; // average value
for (int i = 0; i < n; i++) {
sum += x[i];
}
avg = (float) sum / n; // cast sum to float to get floating-point result
printf("The average of the elements in the array is %.2f\n", avg);
return 0;
}
```
Output:
```
The average of the elements in the array is 3.00
```
Note that the average is calculated by dividing the sum of the elements by the number of elements in the array. To avoid integer division, we cast the sum to a float before dividing. The "%.2f" format specifier in the printf statement is used to print the average with two decimal places.
相关推荐
![text/x-c](https://img-home.csdnimg.cn/images/20210720083646.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)
![](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)