四舍五入 1 有两个浮动数字
rounding 1 to have two floating digits
'''
Your task is to write a function which returns the sum of following series upto nth term(parameter).
Series: 1 + 1/4 + 1/7 + 1/10 + 1/13 + 1/16 +...
'''
有点不平凡,但我尝试使用 round(1,2)
来显示 1.00
但它显示 1.0
,我可以用什么来显示 1.00
在 Python?
def series_sum(n):
# Happy Coding ^_^
sum = 0
for i in range(n):
sum += 1/(1+(3*i))
return round(sum, 2)
这是 codewars 中编码挑战的 return 值,而不是印刷品。所以它应该是 return 而你只需编写方法。
对于数值计算,小数点后的数字应该无关紧要。我相信你想要一个带有 2 个小数位的字符串表示形式。
在 Python 2.x 中,你会做:
>>> "%.2f"%1.0
'1.00'
在 Python3.x,你会做:
>>> "{:.2f}".format(1.0)
'1.00'
使用format
函数:
return format(sum, '.2f')
'''
Your task is to write a function which returns the sum of following series upto nth term(parameter).
Series: 1 + 1/4 + 1/7 + 1/10 + 1/13 + 1/16 +...
'''
有点不平凡,但我尝试使用 round(1,2)
来显示 1.00
但它显示 1.0
,我可以用什么来显示 1.00
在 Python?
def series_sum(n):
# Happy Coding ^_^
sum = 0
for i in range(n):
sum += 1/(1+(3*i))
return round(sum, 2)
这是 codewars 中编码挑战的 return 值,而不是印刷品。所以它应该是 return 而你只需编写方法。
对于数值计算,小数点后的数字应该无关紧要。我相信你想要一个带有 2 个小数位的字符串表示形式。
在 Python 2.x 中,你会做:
>>> "%.2f"%1.0
'1.00'
在 Python3.x,你会做:
>>> "{:.2f}".format(1.0)
'1.00'
使用format
函数:
return format(sum, '.2f')