“str”对象不能解释为整数(Python 3.8)

2024-05-14 17:59:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道这个问题以前被问过很多次,但我无法解决我的代码的问题是什么,以及如何解决它

这是一个温度转换器

import sys
import time
print('This program will convert different units of temperature.')
unit1 = input('What unit do you want to convert from?\nAnswer with the letter C, F or K.\n')
unit2 = input('And what unit to?\nUse the same ruling as the previous question.\n')
temp1 = input('What temperature do you want to convert?.\n')
temp2 = 0

if unit1 == ('C'):
    symbo1one = ('°C')

if unit1 == ('K'):
    symbolone = ('°K')

if unit1 == ('F'):
    symbolone = ('°F')


if unit2 == ('C'):
    symbo12 = ('°C')

if unit2 == ('K'):
    symbol2 = ('°K')

if unit2 == ('F'):
    symbol2 = ('°F')



if unit1 == ('C') and unit2 == ('K'):
    temp2 = ((int(temp1)) + 273.15)
    unitname1 = ('Celsius')
    unitname2 = ('Kelvin')
if unit1 == ('C') and unit2 == ('F'):
    temp2 = ((int(temp1) * (9/5)) + 32)
    unitname1 = ('Celsius')
    unitname2 = ('Farhenheit')
if unit1 == ('K') and unit2 == ('C'):
    temp2 = ((int(temp1)) - 273.15)
    unitname1 = ('Kelvin')
    unitname2 = ('Celsius')
if unit1 == ('K') and unit2 == ('F'):
    temp2 = ((((int(temp1)) - 273.15) * (9/5)) + 32)
    unitname1 = ('Kelvin')
    unitname2 = ('Farhenheit')
if unit1 == ('F') and unit2 == ('C'):
    temp2 = (((int(temp1)) + 32) * (5/9))
    unitname1 = ('Farhenheit')
    unitname2 = ('Celsius')
if unit1 == ('F') and unit2 == ('K'):
    temp2 = ((((int(temp1)) + 32) * (5/9)) + 273.15)
    unitname1 = ('Farhenheit')
    unitname2 = ('Kelvin')
if unit1 == unit2:
    temp2 = temp1

dp = ('To how many decimal places would you like your result given?')

print(('Original Temperature: ') + (str(temp1)) + (symbolone))
time.sleep(1)
print(('Converted Temperature: ') + (round(temp2, (dp))) + (symbol2))
time.sleep(10)
sys.exit()

这就产生了一个错误:

File "C:\Users\rdmor\AppData\Local\Programs\Python\Python38\Temperature.py", line 59, in <module>
    print(('Converted Temperature: ') + (round(temp2, (dp))) + (symbol2))
TypeError: 'str' object cannot be interpreted as an integer

我已经尽了最大的努力,而且我对编程还比较陌生,所以我非常感谢您的一点帮助


Tags: andifintprinttemperaturecelsiuskelvintemp2
2条回答

两件事。在最后几行中,您忘记将input添加到dp中,并且无法将round值添加到字符串中,因此需要将其转换为字符串

这会奏效的

dp = int(input('To how many decimal places would you like your result given?'))
print(('Original Temperature: ') + (str(temp1)) + (symbolone))
time.sleep(1)
print(('Converted Temperature: ') + (str(round(temp2, (dp)))) + (symbol2))
dp = ('To how many decimal places would you like your result given?')

你是想用这个从用户那里得到什么吗?因为,如果你这样做了,它应该是这样的:

dp = int(input('To how many decimal places would you like your result given?'))

相关问题 更多 >

    热门问题