1. 程式人生 > 實用技巧 >codewar刷題--8kyu--Grasshopper - Debug

codewar刷題--8kyu--Grasshopper - Debug

原題目:

Debug celsius converter

Your friend is traveling abroad to the United States so he wrote a program to convert fahrenheit to celsius. Unfortunately his code has some bugs.

Find the errors in the code to get the celsius converter working properly.

To convert fahrenheit to celsius:

celsius = (fahrenheit - 32) * (5/9)

Remember that typically temperatures in the current weather conditions are given in whole numbers. It is possible for temperature sensors to report temperatures with a higher accuracy such as to the nearest tenth. Instrument error though makes this sort of accuracy unreliable for many types of temperature measuring sensors.

大致意思是,需要將溫度做個轉換,把華氏的溫度轉成攝氏的溫度,題目給出了一個公式

celsius = (fahrenheit - 32) * (5/9)

輸入一個華氏溫度,通過函式計算判斷是否高於冰點(0℃),題目給出一個寫好的程式碼,需要將程式碼優化後才能提交。

給的程式碼的bug有很多,執行的時候各種坑,感覺是一個新手菜鳥會犯的很多錯。(提交了答案後找不回來了,不列舉)

按照題目意圖寫了如下程式碼,但是在提交的是,有部分被否定了。

被否程式碼:

1 def weather_info (temp):
2     c =(temp-32)*5/9
3     if (c > 0):
4         return
(str(c) + " is above freezing temperature") 5 else: 6 return (str(c) + " is freezing temperature")
#'252.77777777777777 is above freezing temperature' should equal '252.7777777777778 is above freezing temperature'

查看了其他的解決方法後,發現自己在做計算的時候沒有將c =(temp-32)*5/9 的數字型別轉換程float ,導致精度損失,被否。

修改了程式碼後提交成功了。

成功提交程式碼

1 def weather_info (temp):
2     c =(temp-32.0)*(5.0/9.0)
3     if (c > 0):
4         return (str(c) + " is above freezing temperature")
5     else:
6         return (str(c) + " is freezing temperature")

-------我是分割線

題目給的程式碼找回來了,標紅的都是有問題的程式碼。

1 def weather_info (temp):
2     c : convert(temp) 
3     if (c > 0): 
4         return (c + " is freezing temperature")
5     else:
6         return (c + " is above freezing temperature")
7     
8 def convertToCelsius (temperature):
9   var celsius = (tempertur) - 32 + (5/9)