codewar刷题--8kyu--Grasshopper - Debug
Posted zivaro
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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)
以上是关于codewar刷题--8kyu--Grasshopper - Debug的主要内容,如果未能解决你的问题,请参考以下文章