Python编程练习温度转换
请编写程序将用户输入华氏度转换为摄氏度,或将输入的摄氏度转换为华氏度。
转换算法如下:(C表示摄氏度、F表示华氏度)
C = ( F - 32 ) / 1.8
F = C * 1.8 + 32
要求如下:
我的代码是
emp = input()
if temp[0] == 'C':
result = float('%.2f' % (float(temp[1:])*1.8+32))
print('F'+str(result))
elif temp[0] == 'F':
result = float('%.2f' % ((float(temp[1:])-32)/1.8))
print('C'+str(result))
出现的问题是:是能处理浮点数,输入整数时,输出就不能保留小数点后两位,可能是float(temp[1:])出错了,求解
如输入:F32
输出:C0.0
正确输出是:C0.00
temp = "F32"
if temp[0] == 'C':
result = float('%.2f' % (float(temp[1:])*1.8+32))
print('F{:.2f}'.format(result))
elif temp[0] == 'F':
result = float('%.2f' % ((float(temp[1:])-32)/1.8))
print('C{:.2f}'.format(result))
temp = input("shuru:")
if temp[0] == 'C':
result = float('%.2f' % (float(temp[1:])*1.8+32))
print('F'+str(result))
elif temp[0] == 'F':
result = '%.2f' % ((float(temp[1:])-32.00)/1.80)
print('C'+str(result))
这条代码你原来写法是将 %.2f (此时已经是0.00了)然后你又加强制转换float()因为小数点后面是两个0 所以自动变成0.0只是说是浮点型 而不考虑小数位数,删去float即可
代码如上。
这样就ok了