用c语言统计数组中与全部元素平均值相同的元素的个数
时间: 2023-08-31 11:05:46 浏览: 58
以下是用 C 语言实现统计数组中与全部元素平均值相同的元素的个数的代码:
```c
#include <stdio.h>
int main() {
int arr[] = {1, 2, 3, 4, 5, 6};
int len = sizeof(arr) / sizeof(arr[0]);
int sum = 0, i, count = 0;
float avg;
for (i = 0; i < len; i++) {
sum += arr[i];
}
avg = (float)sum / len;
for (i = 0; i < len; i++) {
if (arr[i] == avg) {
count++;
}
}
printf("平均数为 %.2f,数组中与平均数相同的元素个数为 %d\n", avg, count);
return 0;
}
```
首先,我们定义了一个整型数组 `arr`,并初始化了它的值。然后,我们计算该数组的长度,并通过一个循环累加数组中所有元素的值,以便计算平均数。接下来,我们再次循环数组,如果当前元素等于平均数,则增加 `count` 变量的值。最后,我们输出平均数和数组中与平均数相同的元素个数。
相关问题
用c语言统计数组中与全部元素平均值相同的元素的个数intfun
以下是用C语言编写的统计数组中与全部元素平均值相同的元素的个数的函数intfun:
```c
#include <stdio.h>
int intfun(int arr[], int size){
int sum = 0, i, count = 0;
float avg;
for(i=0; i<size; i++){
sum += arr[i];
}
avg = (float)sum/size;
for(i=0; i<size; i++){
if(arr[i] == avg){
count++;
}
}
return count;
}
int main(){
int arr[] = {2, 4, 6, 8, 10};
int size = sizeof(arr)/sizeof(arr[0]);
int result = intfun(arr, size);
printf("The number of elements that are equal to the average of all elements is: %d", result);
return 0;
}
```
在这个函数中,我们先求出了数组中所有元素的总和,并计算了平均值。然后,我们遍历整个数组,如果某个元素等于平均值,则将计数器加一。最后,返回计数器的值,即为数组中与全部元素平均值相同的元素的个数。
在主函数中,我们定义了一个数组arr和它的大小size,并调用intfun函数来计算与平均值相同的元素的个数,并将结果打印出来。
用c语言编写程序统计数组中大于数组元素平均值的元素的个数
```c
#include <stdio.h>
int main()
{
int n, sum = 0;
float average;
printf("请输入数组元素个数:");
scanf("%d", &n);
int a[n];
printf("请输入%d个整数:", n);
for (int i = 0; i < n; i++)
{
scanf("%d", &a[i]);
sum += a[i];
}
average = (float)sum / n;
int count = 0;
for (int i = 0; i < n; i++)
{
if (a[i] > average)
{
count++;
}
}
printf("大于平均值%.2f的元素个数为:%d\n", average, count);
return 0;
}
```
相关推荐
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)