n个人分配100元钱,用户输入由n不同取值构成的列表,输出各种情況每人所分数额 (分行输出,保留2位小数)。如果发生ZeroDixisionError则输出can’t be 0:其他错误输出Error。列表元素处理完毕后输出over。 要求:用try语句处理异常。
时间: 2023-07-15 21:15:35 浏览: 46
以下是一个可能的解决方案:
```python
try:
nums = input("请输入由n不同取值构成的列表,以逗号分隔:").split(",")
n = len(nums)
nums = [int(num) for num in nums]
total = 100
for i in range(n):
if nums[i] == 0:
print("can't be 0")
else:
amount = round(total / sum(nums) * nums[i], 2)
print(f"第{i+1}个人分得{amount}元")
print("over")
except ZeroDivisionError:
print("can't be 0")
except Exception:
print("Error")
```
首先,我们使用 `try` 语句来捕获可能出现的异常。然后,我们让用户输入由 n 个不同取值构成的列表,并对列表进行处理,转换为整数类型。接下来,我们计算每个人分得的钱数,如果分母为 0 则会触发 `ZeroDivisionError` 异常;如果其他错误则捕获所有异常。最后,我们分行输出每个人分得的钱数,并在最后输出 "over" 表示程序结束。
相关问题
n个人平均分配100元钱,用户输入由n不同取值构成的列表,输出各种情况每人所分数额(分行输出,保留两位小数)。如果发生ZeroDivisionError则输出can't be 0;其他错误输出Error。列表元素处理完毕后输出over
好的,让我来帮你解决这个问题。下面是 Python 的代码实现:
```python
while True:
try:
n_list = list(map(int, input().split()))
for n in n_list:
if n == 0:
print("can't be 0")
continue
res = 100 / n
print("{:.2f}".format(res))
except ZeroDivisionError:
print("can't be 0")
except:
print("Error")
else:
print("over")
break
```
你可以输入一个由多个整数构成的列表,程序会自动输出每种情况下每个人所分的数额,每个数额占一行,保留两位小数。如果出现分母为 0 的情况,会输出 can't be 0;如果出现其他错误,会输出 Error。当处理完所有输入后,会输出 over 并结束程序。
希望能帮到你!
n个人平均分配100元钱,用户输入由n不同取值构成的列表,输出各种情况每人所分数额(分行输出,保留2位小数)。如果发生ZeroDivisionError则输出can't be 0;其他错误输出Error。列表元素处理完毕后输出over。要求:用try语句处理异常
好的,我理解你的问题了。这里是一个可能的解决方案:
```python
while True:
try:
n_list = input().split() # 输入由n不同取值构成的列表
if not n_list: # 如果列表为空则结束程序
print("over")
break
for n in n_list:
n = int(n)
if n == 0: # 如果n为0则输出can't be 0
print("can't be 0")
else:
result = round(100/n, 2) # 平均分配100元钱
print(result)
except ZeroDivisionError: # 处理ZeroDivisionError异常
print("can't be 0")
except Exception as e: # 处理其他异常
print("Error")
```
这个程序会不断循环,每次读取一行输入。如果输入是空行,则程序结束。对于每个输入的n,程序会尝试将其转换为整数,然后计算每人分配的金额,并输出结果。如果n为0,则输出"can't be 0";如果发生ZeroDivisionError异常,则也输出"can't be 0";如果发生其他异常,则输出"Error"。最后,如果输入为空,则输出"over"结束程序。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)