# TempConvert.py TempStr = input("请输入带有符合的温度值:") if TempStr[-1] in ['F', 'f']: C = (eval(TempStr[0:-1]) - 32) / 1.8 print("转换后的温度是{:.2f}C".format(C)) elif TempStr[-1] in ['C', 'c']: F = 1.8 * eval(TempStr[0:-1]) + 32 print("转换后的温度是{:.2f}F".format(F)) else: print("输入格式错误")将其的输入输出温度单位放在首位
时间: 2024-03-02 14:50:36 浏览: 27
好的,这是修改后的代码:
```python
def convert_temperature():
temp_str = input("请输入温度值(格式示例:12C,99F):")
unit = temp_str[-1]
temp = eval(temp_str[:-1])
if unit in ['F', 'f']:
celsius = (temp - 32) * 5 / 9
print("转换后的温度是{:.2f}C".format(celsius))
elif unit in ['C', 'c']:
fahrenheit = 1.8 * temp + 32
print("转换后的温度是{:.2f}F".format(fahrenheit))
else:
print("输入格式错误")
convert_temperature()
```
在这个版本中,我们将输入的温度值改为了一个字符串,其中最后一个字符表示温度单位,前面的数字则是温度数值。在函数中,我们首先将单位和温度值分别提取出来,然后进行转换计算。
输出结果中,我们将转换后的温度单位放在了后面,更符合输入和输出的对称性。
相关问题
# TempConvert.py TempStr = input("请输入带有符合的温度值:") if TempStr[-1] in ['F', 'f']: C = (eval(TempStr[0:-1]) - 32) / 1.8 print("转换后的温度是{:.2f}C".format(C)) elif TempStr[-1] in ['C', 'c']: F = 1.8 * eval(TempStr[0:-1]) + 32 print("转换后的温度是{:.2f}F".format(F)) else: print("输入格式错误")
好的,我来帮你改写这个程序。以下是改写后的代码:
```python
def convert_temperature():
temp_str = input("请输入带有符号的温度值:")
if temp_str[-1] in ['F', 'f']:
celsius = (eval(temp_str[0:-1]) - 32) * 5 / 9
print("转换后的温度是{:.2f}C".format(celsius))
elif temp_str[-1] in ['C', 'c']:
fahrenheit = 1.8 * eval(temp_str[0:-1]) + 32
print("转换后的温度是{:.2f}F".format(fahrenheit))
else:
print("输入格式错误")
convert_temperature()
```
修改后的程序将原来的代码放入了一个函数 `convert_temperature()` 中。函数名和参数名都采用了 Python 的命名规范,变量名也进行了修改,更符合可读性。
在摄氏度转华氏度的计算中,将除以 1.8 的操作改为了乘以 5 / 9,这样可以更加精准地表示摄氏度转化为华氏度的计算。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![xlsx](https://img-home.csdnimg.cn/images/20210720083732.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)