首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >四舍五入到10点

四舍五入到10点
EN

Stack Overflow用户
提问于 2013-09-06 14:34:40
回答 3查看 177关注 0票数 1

我是Python的初学者。我想把密码转到每10分钟一次,例如。从33岁到30岁

以下是目前为止的代码:

代码语言:javascript
复制
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.

我该怎么解决呢?

EN

回答 3

Stack Overflow用户

发布于 2013-09-06 14:37:07

定义您自己的功能:

代码语言:javascript
复制
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()转换:

代码语言:javascript
复制
>>> 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.
票数 2
EN

Stack Overflow用户

发布于 2013-09-06 14:38:07

您可以简单地做这样的事情:

代码语言:javascript
复制
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."

希望它能帮上忙

票数 0
EN

Stack Overflow用户

发布于 2013-09-06 14:50:46

你可以:

代码语言:javascript
复制
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。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18660303

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档