1

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

我如何解决它?

4

3 回答 3

2

定义自己的函数:

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

>>> def roundoff(a, b):
...        b = b - (b % 10)
...        print "{} you are around {} years old.".format(a, b)
...     
>>> roundoff('bob', 33)
bob you are around 30 years old.
>>> roundoff('bob', 97)
bob you are around 90 years old.
于 2013-09-06T14:37:07.610 回答
0

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

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."

希望它有所帮助

于 2013-09-06T14:38:07.487 回答
0

你可以做:

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。

于 2013-09-06T14:50:46.963 回答