python摄氏度和华氏度温度转换
要求
温度的刻画有两个不同体系:摄氏度(celsius)和华氏度(fahrenheit)。
请编写程序将用户输入华氏度转换为摄氏度,或将输入的摄氏度转换为华氏度。
转换算法如下:(c表示摄氏度、f表示华氏度)
c = ( f - 32 ) / 1.8 f = c * 1.8 + 32
要求如下:
(1) 输入输出的摄氏度可采用大小写字母c结尾,温度可以是整数或小数,如:12.34c指摄氏度12.34度;
(2) 输入输出的华氏度可采用大小写字母f结尾,温度可以是整数或小数,如:87.65f指华氏度87.65度;
(3) 输出保留小数点后两位,输入格式错误时,输出提示:输入格式错误;
(4) 使用input()获得测试用例输入时,不要增加提示字符串。
第一种写法
while true:
tem = input("请输入带符号的温度:")
if tem[-1] == "c" or tem[-1] == "c":
a = float(tem[0:-1])
b = a * 1.8 + 32
c = format(b, ".2f")
result = str(c)
print("转换后的温度是:{}f".format(result))
elif tem[-1] == "f" or tem[-1] == "f":
a = float(tem[0:-1])
b = (a - 32) / 1.8
c = format(b, ".2f")
result = str(c)
print("转换后的温度是:{}c".format(result))
else:
print("格式输入错误")第二种写法
while true:
temstr=input("请输入带符号的温度值:")
if temstr[-1] in ['f','f']:
c = (eval(temstr[0:-1]) -32)/1.8
print("转换后的温度:{0:.2f}c".format(c))
elif temstr[-1] in ['c','c']:
f = 1.8*eval(temstr[0:-1])+32
print("转换后的温度是;{0:.2f}f".format(f))
else:
print("输入格式错误")总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论