用C语言实现从键盘输入10个整数到数组中,求其中正数的个数及正数的平均值,并输出结果。
时间: 2024-05-11 21:19:37 浏览: 137
下面是用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语言从键盘输入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语言程序:利用指针实现从键盘输入若干个数放入一个一维数组中(数组长度自定义),用0结束输入并放在最后一个元素中。通过指针输出数组的所有元素、正数的个数,负数的个数以及正数平均值。
以下是一个实现此功能的 C 语言程序:
```c
#include <stdio.h>
int main() {
int nums[100]; // 定义一个最大长度为 100 的数组
int *p = nums; // 定义一个指针指向数组的第一个元素
int num, count_pos = 0, count_neg = 0, sum_pos = 0, len = 0;
// 输入数据
printf("请输入若干个整数(以0结束):");
do {
scanf("%d", &num);
*p++ = num;
len++;
} while (num != 0 && len < 100); // 最多输入 100 个数
p = nums; // 指向数组的第一个元素
// 输出数组的所有元素
printf("数组的所有元素为:");
while (*p != 0) {
printf("%d ", *p);
if (*p > 0) {
count_pos++;
sum_pos += *p;
} else if (*p < 0) {
count_neg++;
}
p++;
}
// 计算正数的平均值
float avg_pos = count_pos > 0 ? (float) sum_pos / count_pos : 0.0;
// 输出结果
printf("\n正数的个数为:%d\n负数的个数为:%d\n正数的平均值为:%.2f\n", count_pos, count_neg, avg_pos);
return 0;
}
```
程序的执行过程如下:
```
请输入若干个整数(以0结束):1 2 -3 4 5 0
数组的所有元素为:1 2 -3 4 5
正数的个数为:3
负数的个数为:1
正数的平均值为:2.67
```
阅读全文
相关推荐
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![java](https://img-home.csdnimg.cn/images/20250102104920.png)
![c](https://img-home.csdnimg.cn/images/20250102104920.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)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)