我對 Python 很陌生,但對學(xué)習(xí)很感興趣。對于 uni Python 課程,我將創(chuàng)建一個程序,將溫度轉(zhuǎn)換為攝氏度或華氏度,并將轉(zhuǎn)換顯示為小數(shù)點后第一個位。我的問題在于我的打印線。正如您在我的代碼中看到的,我嘗試在連接時使用 round() 函數(shù)。雖然我試圖將浮點數(shù)轉(zhuǎn)換為 str(),但當(dāng)我運行我的程序時,出現(xiàn)以下錯誤。類型錯誤:類型 str 未定義圓形方法對于以下行打印 (round(str(temp), 1)+ " 攝氏度 = " + str(degF) + " 華氏度。")和我的 elif 集團中的打印線類似。任何幫助理解和解決問題將不勝感激。temp=float(input("Enter a temperature value to convert: "))unit=str(input("Convert to Fahrenheit or Celsius? Enter f or c: "))if unit=="c" or unit == "C": degC=(temp) temp=(1.8*temp)+32 print (round(str(temp), 1) + " degrees fahrenheit = " + str(degC) + " degrees Celsius. ")elif unit=="f" or unit == "F": degF=(temp) temp=(temp-32)/1.8 print (round(str(temp), 1)+ " degrees celsius = " + str(degF) + " degrees Fahrenheit. ")else: print("you did not enter an f or c. Goodbye ")我的輸出應(yīng)該四舍五入到第一個小數(shù)位。
3 回答

一只斗牛犬
TA貢獻1784條經(jīng)驗 獲得超2個贊
除非這是使用round函數(shù)的課堂作業(yè),否則我認為不需要round函數(shù)。
print ("%.1f degrees Celsius = %.1f degrees Fahrenheit" % (temp, degC))

Helenr
TA貢獻1780條經(jīng)驗 獲得超4個贊
不要轉(zhuǎn)換temp
為字符串。將其保留為round
. 將結(jié)果 afterround
變成str
for 連接
str(round(temp, 1))

蕭十郎
TA貢獻1815條經(jīng)驗 獲得超13個贊
您的操作順序錯誤。先舍入,再轉(zhuǎn)換為字符串:
print (str(round(temp), 1)+ " degrees celsius = " ...
添加回答
舉報
0/150
提交
取消