Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/283.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 四舍五入到10';s_Python_Rounding - Fatal编程技术网

Python 四舍五入到10';s

Python 四舍五入到10';s,python,rounding,Python,Rounding,我是Python的初学者。我想把代码四舍五入到每10,例如从33到30 以下是迄今为止的代码: 如何修复它?定义您自己的功能: 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()转换: >>>

我是Python的初学者。我想把代码四舍五入到每10,例如从33到30

以下是迄今为止的代码:

如何修复它?

定义您自己的功能:

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.

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

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。

我喜欢这个答案,但如果OP想要将结果四舍五入为97呢?这个问题还不清楚,但看看算法会有什么不同可能会很有趣。@SethMMorton然后我们可以使用:
int(round(97/10.0)*10)
def roundoff(name, age):
    print '%s, you are around %d years old.' % (name, (age /10) * 10)