(1)设计程序,可交互输入若干个整数,求其和,直到结束标志999为止。在输入过程中,若输入非整数,则忽略。 (2)修改第1题程序,通过对负数输入产生异常的方式,对输入的负数不进行累加运算。
时间: 2024-05-03 18:22:12 浏览: 21
(1)
```python
def sum_until_999():
total = 0
while True:
num_str = input("请输入一个整数(输入999结束):")
if num_str == "999":
break
try:
num = int(num_str)
total += num
except ValueError:
print("输入有误,请输入整数。")
print("输入的整数和为:", total)
```
(2)
```python
class NegativeNumberError(Exception):
pass
def sum_until_999_no_negative():
total = 0
while True:
num_str = input("请输入一个整数(输入999结束):")
if num_str == "999":
break
try:
num = int(num_str)
if num < 0:
raise NegativeNumberError("输入的数字为负数")
total += num
except ValueError:
print("输入有误,请输入整数。")
except NegativeNumberError as e:
print(e)
print("输入的正整数和为:", total)
```
相关推荐
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)