统计正数负数和零的个数
时间: 2023-10-25 19:27:38 浏览: 59
好的,这个问题很简单,可以使用一个循环遍历整个数列,然后分别统计正数、负数和零的个数。下面是一个Python代码示例:
```python
nums = [2, 0, -5, 1, 3, -2, 0, 7, -4, 0]
positive_count = 0
negative_count = 0
zero_count = 0
for num in nums:
if num > 0:
positive_count += 1
elif num < 0:
negative_count += 1
else:
zero_count += 1
print("Positive numbers:", positive_count)
print("Negative numbers:", negative_count)
print("Zeros:", zero_count)
```
输出结果为:
```
Positive numbers: 4
Negative numbers: 3
Zeros: 3
```
这个代码可以适用于任何整数数列。
相关问题
统计正数和负数的个数
统计正数和负数的个数可以通过遍历整个数列,对每个数进行判断,如果是正数则正数计数器加1,如果是负数则负数计数器加1。具体实现可以参考以下伪代码:
```
positive_count = 0
negative_count = 0
for num in nums:
if num > 0:
positive_count += 1
elif num < 0:
negative_count += 1
```
其中,`nums`是待统计的数列,`positive_count`和`negative_count`分别是正数和负数的计数器。遍历整个数列后,`positive_count`和`negative_count`的值就是正数和负数的个数。
统计正数和负数的个数py
以下是一个简单的 Python 代码,用于统计列表中正数和负数的个数:
```python
nums = [1, -2, 3, -4, 5, 6, -7, -8, 9]
positive_count = 0
negative_count = 0
for num in nums:
if num > 0:
positive_count += 1
elif num < 0:
negative_count += 1
print("正数个数为:", positive_count)
print("负数个数为:", negative_count)
```
输出结果:
```
正数个数为: 4
负数个数为: 4
```
以上代码中,我们首先定义了一个包含正数和负数的列表 nums。然后,我们使用 for 循环遍历列表中的每个元素,并根据元素是否大于零或小于零来增加正数和负数计数器的值。最后,我们打印出正数和负数的个数。
相关推荐
![asm](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)