首页 > 解决方案 > 'str' 对象不能解释为整数(Python 3.8)

问题描述

我知道这个问题之前已被多次问过,但我无法弄清楚我的代码存在什么问题以及如何解决它。

这是一个温度转换器

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

我已经尽力了,而且我对编程还比较陌生,所以我们将不胜感激

标签: pythonstring

解决方案


两件事情。在您的最后几行中,您忘记添加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))

推荐阅读