编写程序,输入上网的时间计算上网费用,计算的方法如下: 【25元 <10小时 费用 =每小时 2.5元 10~50小时 [每小时2元 ≥50小时 同时,为了鼓励多上网,每月收费最多不超过 130元。 要求:使用 switch 语句编程。
时间: 2023-05-31 10:02:19 浏览: 65
```python
hours = int(input("请输入上网时间(单位:小时):"))
if hours <= 0:
print("请输入正确的上网时间!")
else:
if hours <= 10:
fee = hours * 2.5
elif hours <= 50:
fee = 25 + (hours - 10) * 2
else:
fee = 105 # 50小时以上的费用为 105 元
if fee > 130:
fee = 130
print("本次上网费用为 %.2f 元。" % fee)
```
使用 `switch` 语句实现:
```python
hours = int(input("请输入上网时间(单位:小时):"))
if hours <= 0:
print("请输入正确的上网时间!")
else:
fee = 0
switcher = {
1: 2.5,
2: 2.5,
3: 2.5,
4: 2.5,
5: 2.5,
6: 2.5,
7: 2.5,
8: 2.5,
9: 2.5,
10: 2.5,
11: 2,
12: 2,
13: 2,
14: 2,
15: 2,
16: 2,
17: 2,
18: 2,
19: 2,
20: 2,
21: 2,
22: 2,
23: 2,
24: 2,
25: 2,
26: 2,
27: 2,
28: 2,
29: 2,
30: 2,
31: 2,
32: 2,
33: 2,
34: 2,
35: 2,
36: 2,
37: 2,
38: 2,
39: 2,
40: 2,
41: 2,
42: 2,
43: 2,
44: 2,
45: 2,
46: 2,
47: 2,
48: 2,
49: 2,
50: 2,
}
for i in range(hours):
fee += switcher.get(i+1, 2) # 默认每小时 2 元
if fee > 130:
fee = 130
print("本次上网费用为 %.2f 元。" % fee)
```
以上两种方法中,第一种是直接使用条件语句,第二种是使用 `switch` 语句实现。由于 Python 中没有 `switch` 语句,因此需要使用字典来模拟。