编程从键盘输入k的值及k个整数,统计其中的正数、零和负数的个数。
时间: 2023-05-23 12:05:48 浏览: 165
A:
```python
k = int(input("请输入数列的长度:"))
lst = []
for i in range(k):
lst.append(int(input("请输入第{}个整数:".format(i+1))))
positive_num = 0
zero_num = 0
negative_num = 0
for num in lst:
if num > 0:
positive_num += 1
elif num == 0:
zero_num += 1
else:
negative_num += 1
print("正数的个数为:", positive_num)
print("零的个数为:", zero_num)
print("负数的个数为:", negative_num)
```
输入样例:
```
请输入数列的长度:5
请输入第1个整数:3
请输入第2个整数:-2
请输入第3个整数:0
请输入第4个整数:5
请输入第5个整数:-7
```
输出样例:
```
正数的个数为: 2
零的个数为: 1
负数的个数为: 2
```
相关问题
编程实现从键盘输入k的值及个整数,统计其中正数、零和负数的个数。c语言
好的,以下是C语言的代码实现:
```c
#include <stdio.h>
int main() {
int k, num, positive = 0, zero = 0, negative = 0;
printf("请输入k的值:");
scanf("%d", &k);
for (int i = 0; i < k; i++) {
printf("请输入第%d个整数:", i + 1);
scanf("%d", &num);
if (num > 0) {
positive++;
} else if (num == 0) {
zero++;
} else {
negative++;
}
}
printf("正数个数:%d\n", positive);
printf("零的个数:%d\n", zero);
printf("负数个数:%d\n", negative);
return 0;
}
```
代码的思路是:首先从键盘输入一个整数k,表示要输入k个整数。然后用for循环输入k个整数,并统计其中正数、零和负数的个数。最后输出统计结果。
统计正数、负数和零的个数从键盘输入10 个整数
当你需要统计从键盘输入的10个整数中有多少正数、多少负数以及多少零时,可以编写一个简单的程序来处理这种情况。以下是步骤:
1. 首先,创建一个变量分别记录正数(通常是整型,并初始化为0)、负数(同样初始化为0)和零的数量(初始化为0)。
2. 使用循环结构(如for或while),读取用户输入的10个整数。每次输入后,检查该数字是否大于0,小于0还是等于0。
- 如果数字大于0,增加正数计数器。
- 如果数字小于0,增加负数计数器。
- 如果数字等于0,增加零的计数器。
3. 循环结束后,你会得到每个类型的整数的个数。
例如,在Python中,你可以这样做:
```python
count_positive = count_negative = count_zero = 0
for _ in range(10):
num = int(input("请输入一个整数:"))
if num > 0:
count_positive += 1
elif num < 0:
count_negative += 1
else:
count_zero += 1
print(f"正数有 {count_positive} 个,负数有 {count_negative} 个,零有 {count_zero} 个。")
```
阅读全文
相关推荐














