.从键盘输入5个整数到数组中,求负数的个数及其平均值,并输出结果,其中平均值精确到小数点后四位(若负数的个数为0,输出负数的个数及字符串“无平均值”)。用c语言解答
时间: 2023-06-06 08:08:59 浏览: 72
以下是代码实现:
```
#include<stdio.h>
int main() {
int n, count = 0, sum = 0, negCount = 0;
float avg;
int arr[5];
printf("请输入5个整数:\n");
for(int i=0; i<5; i++) {
scanf("%d", &n);
arr[i] = n;
if(n < 0) {
negCount++;
sum += n;
}
}
if(negCount == 0) {
printf("负数的个数为0,无平均值\n");
} else {
avg = (float)sum / negCount;
printf("负数的个数为%d,平均值为%.4f\n", negCount, avg);
}
return 0;
}
```
运行结果示例:
```
请输入5个整数:
-1 2 -3 4 0
负数的个数为2,平均值为-2.0000
```
```
请输入5个整数:
0 1 2 3 4
负数的个数为0,无平均值
```
相关问题
c语言从键盘输入10个整数到数组中,求其中正数的个数及其平均值,并输入结果。
好的,以下是C语言代码实现:
```c
#include <stdio.h>
int main() {
int arr[10];
int count = 0, sum = 0;
float avg;
// 从键盘输入10个整数到数组中
printf("请输入10个整数:\n");
for (int i = 0; i < 10; i++) {
scanf("%d", &arr[i]);
}
// 求其中正数的个数及其平均值
for (int i = 0; i < 10; i++) {
if (arr[i] > 0) {
count++;
sum += arr[i];
}
}
// 计算平均值
avg = (float)sum / count;
// 输出结果
printf("正数的个数为:%d\n", count);
printf("正数的平均值为:%.2f\n", avg);
return 0;
}
```
运行程序后,输入10个整数,程序会输出其中正数的个数及其平均值。
用C语言实现从键盘输入10个整数到数组中,求其中正数的个数及正数的平均值,并输出结果。
下面是用C语言实现从键盘输入10个整数到数组中,求其中正数的个数及正数的平均值的代码:
```c
#include <stdio.h>
int main() {
int arr[10], count = 0, sum = 0;
float avg;
// 从键盘输入10个整数到数组中
printf("请输入10个整数:\n");
for (int i = 0; i < 10; i++) {
scanf("%d", &arr[i]);
}
// 统计正数的个数及其和
for (int i = 0; i < 10; i++) {
if (arr[i] > 0) {
count++;
sum += arr[i];
}
}
// 计算正数的平均值
if (count > 0) {
avg = (float) sum / count;
} else {
avg = 0;
}
// 输出结果
printf("正数的个数为:%d\n", count);
printf("正数的平均值为:%.2f\n", avg);
return 0;
}
```
运行结果示例:
```
请输入10个整数:
-2 1 3 -5 2 -1 4 0 6 -2
正数的个数为:4
正数的平均值为:3.50
```
相关推荐
![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)