2024-09-27 23:21:11 发布
网友
我是Python的初学者。我想把代码四舍五入到每10秒,比如从33到30。在
def roundoff(a, b): b = round(b) print str(a) + " you are around " + str(b) + " years old." >>> roundoff("Bob", 33) Bob you are around 33.0 years old.
我怎么修?在
您可以简单地执行以下操作:
def roundoff(name,age): age = age - age%10 #the % operator will get the rest of the division by 10 #(so from 33 will get 3) print str(name) + " you are around " + str(age) + " years old."
希望有帮助
您可以:
def roundoff(name, age): print '%s, you are around %d years old.' % (name, (age /10) * 10)
当/运算符将int除以int时,它将返回另一个int。因此,当您将33除以10时,结果将是3而不是3.3。在这之后,你只需要把结果乘以10。在
/
定义自己的功能:
def my_round(x): return x - (x % 10) #or py2.x: (b/10)*10, py3.x: (b//10)*10 ... >>> my_round(33) 30 >>> my_round(333) 330
使用字符串格式,而不是使用串联和str()转换:
str()
您可以简单地执行以下操作:
希望有帮助
您可以:
当
/
运算符将int除以int时,它将返回另一个int。因此,当您将33除以10时,结果将是3而不是3.3。在这之后,你只需要把结果乘以10。在定义自己的功能:
使用字符串格式,而不是使用串联和
^{pr2}$str()
转换:相关问题 更多 >
编程相关推荐