四舍五入到10

2024-09-27 23:21:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我是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.

我怎么修?在


Tags: 代码youdefoldarearoundbobprint
3条回答

您可以简单地执行以下操作:

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()转换:

^{pr2}$

相关问题 更多 >

    热门问题