n个人平均分配100元钱,用户输入由n不同取值构成的列表,输出各种情况每人所分数额(分行输出,保留两位小数)。如果发生ZeroDivisionError则输出can't be 0;其他错误输出Error。列表元素处理完毕后输出over
时间: 2024-02-19 22:03:25 浏览: 26
好的,让我来帮你解决这个问题。下面是 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"结束程序。
Python编写程序,n个人平均分配100元,用户输入由n个不同取值构成的列表,输出各种情况每人所分数额(分行输出,保留2位小数)。如果发生ZeroDivisionError则输出c;其他错误输出Error,列表元素处理完毕后,输出over,用try语句处理异常
可以使用以下代码实现:
```python
try:
values = input("请输入由n个不同取值构成的列表(用逗号隔开):").split(",")
n = len(values)
values = list(map(float, values))
total = sum(values)
if total == 0:
raise ZeroDivisionError
for value in values:
print("{:.2f}".format(value * 100 / total))
except ZeroDivisionError:
print("c")
except:
print("Error")
finally:
print("over")
```
解释一下程序的实现过程:
1. 使用 `input` 函数获取用户输入的列表,使用 `split` 函数将其转换为字符串列表;
2. 使用 `len` 函数获取列表长度,使用 `map` 函数将列表转换为浮点数列表;
3. 使用 `sum` 函数计算列表元素的总和,如果总和为 0,则抛出 `ZeroDivisionError` 异常;
4. 遍历列表,计算每个人分配的数额,使用 `format` 函数保留 2 位小数并输出;
5. 在 try 语句中捕获 `ZeroDivisionError` 异常并输出 "c",捕获其他异常并输出 "Error";
6. 使用 `finally` 语句输出 "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://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)