Codingbat roundsum 逻辑解释
Codingbat roundsum Logic explanation
您好,我正在 Python 中做圆和练习,但我不太了解练习背后的逻辑。这是练习的描述:
For this problem, we'll round an int value up to the next multiple of 10 if its rightmost digit is 5 or more, so 15 rounds up to 20. Alternately, round down to the previous multiple of 10 if its rightmost digit is less than 5, so 12 rounds down to 10. Given 3 ints, a b c, return the sum of their rounded values. To avoid code repetition, write a separate helper "def round10(num):" and call it 3 times. Write the helper entirely below and at the same indent level as round_sum().
这是代码:
def round_sum(a, b, c):
def round10(n):
return (n+5)/10*10
return round10(a) + round10(b) + round10(c)
预期输出:
round_sum(16, 17, 18) → 60
我 运行 coding bat 上的代码并且它按预期工作,但我不理解 round10 方法的逻辑,而且,当我 运行 我计算机中的代码不在 coding bat 中时站点输出为 66.0
请记住,在 python3 中,/ 运算符除以小数,但 // 运算符不会 return 逗号后面的值,因此如果 n = 12。
12 + 5 = 17 // 10 = 1 * 10 -> 10
这就是向上或向下舍入的方式。你也可以用 18 来测试它,这样我们就可以看到它是如何四舍五入的。
18 + 5 = 23 // 10 = 2 * 10 -> 20
您好,我正在 Python 中做圆和练习,但我不太了解练习背后的逻辑。这是练习的描述:
For this problem, we'll round an int value up to the next multiple of 10 if its rightmost digit is 5 or more, so 15 rounds up to 20. Alternately, round down to the previous multiple of 10 if its rightmost digit is less than 5, so 12 rounds down to 10. Given 3 ints, a b c, return the sum of their rounded values. To avoid code repetition, write a separate helper "def round10(num):" and call it 3 times. Write the helper entirely below and at the same indent level as round_sum().
这是代码:
def round_sum(a, b, c):
def round10(n):
return (n+5)/10*10
return round10(a) + round10(b) + round10(c)
预期输出: round_sum(16, 17, 18) → 60 我 运行 coding bat 上的代码并且它按预期工作,但我不理解 round10 方法的逻辑,而且,当我 运行 我计算机中的代码不在 coding bat 中时站点输出为 66.0
请记住,在 python3 中,/ 运算符除以小数,但 // 运算符不会 return 逗号后面的值,因此如果 n = 12。
12 + 5 = 17 // 10 = 1 * 10 -> 10
这就是向上或向下舍入的方式。你也可以用 18 来测试它,这样我们就可以看到它是如何四舍五入的。
18 + 5 = 23 // 10 = 2 * 10 -> 20