【问题标题】:Python3 - Round up combination like thisPython3 - 像这样汇总组合
【发布时间】:2021-02-07 23:21:47
【问题描述】:

我有一个浮点数组合(min_number,max_number),我期待以下汇总:

(-19.12, 34.45) "rounded to" (-19.2, 34.5)
(-0.34, -0.22) "rounded to" (-0.4, -0.3)
(-0.58, -0.87) "rounded to" (-0.6, -0.9)
(-0.24, 5.98) "rounded to" (-0.3, 6.0)
(2.57, 22.38) "rounded to" (2.6, 22.4)

请注意,只需要一位小数。然后:

size = int(input('please input: '))
number = (min_number + max_number) / size

那么“数字”也需要四舍五入,还需要一位小数:

10.233333 "rounded to" 10.3
5.744542267888 "rounded to" 5.8

有什么想法吗?非常感谢,

【问题讨论】:

标签: python-3.x math decimal rounding


【解决方案1】:

只需乘以 10,四舍五入再除以 10

import math
num = input("Round a number:")
num = num.split()
print( math.ceil( float(num[0]) * 10 ) / 10,  math.ceil( float(num[1]) * 10 ) / 10 )

注意:正如@0 0 指出的那样,如果你想对负数进行舍入,这对负数不起作用,那么你需要为它们添加一个 if 语句并使用math.floor

【讨论】:

  • 谢谢 Yash,我还有问题,你能看到我最新的帖子吗?
  • 好的,我去看看
  • 为什么是num[0]?这将只取输入字符串的第一个字符,所以如果输入是12.34,它将只使用1。如果您在问题中引用元组,则应更改输入。
  • 请注意,对于负数,这不会从零舍入。使用问题中的第一个示例,-19.12math.ceil( float(-19.12) * 10 ) / 10 结果为-19.1,而不是-19.2
  • 我使用元组作为输入
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-08-28
  • 2022-11-28
  • 1970-01-01
  • 2017-06-17
  • 1970-01-01
  • 1970-01-01
  • 2018-11-29
相关资源
最近更新 更多