【问题标题】:Rounding an int number to another int number将一个 int 数舍入为另一个 int 数
【发布时间】:2016-12-21 21:16:48
【问题描述】:
while(potatosconeflour <= c1) {
    potatosconeflour = potatosconeflour + potatosconeflour;
}

我使用了一个 while 循环,它在输入数字 24 后不起作用。我正在尝试将一个 int 数舍入到另一个 int 数。例如,我想将任何数字四舍五入为 8 的倍数。

例如:将 1 舍入到 8、13 到 16、23 到 24

【问题讨论】:

  • 您好,欢迎来到stackoverflow!请向我们展示更多您的代码 - 当前的摘录不足以找到问题。

标签: java int rounding


【解决方案1】:

我将源数字除以数字以将其四舍五入(注意:将其转换为 double,因此您不要使用整数除法!)使用 Math.ceil 将结果向上舍入,然后相乘它返回相同的数字:

public static int roundToMultiple(int toRound, int roundBy) {
    return roundBy * (int) Math.ceil((double)toRound / roundBy);
}

【讨论】:

  • 这是错误的。不能使用 Math.round,roundToMultiple(1,8) 会返回 0
  • Math.round 舍入到最接近的 int,因此 1/8 将舍入为 0,然后 0 * 8 = 0。您需要改用 Math.ceil
  • @Marcelo 你是对的。 OP 使用了圆形这个词,尽管他实际上是指天花板,这让我很失望。我已经相应地编辑了我的答案。
【解决方案2】:

如果您想四舍五入到 8 的 最近倍数,那就是 ((i + 3) / 8) * 8。 (如果是8n + 4,则向下取整。如果您想从一半向上取整,请使用i + 4 而不是i + 3。如果您想“一直向上”四舍五入,请使用916 i + 7.)

【讨论】:

  • 感谢您的帮助。如果我想四舍五入到 225 的倍数,我会使用什么
  • 一般来说就是((i + (n/2)) / n) * n
【解决方案3】:

使用返回余数的模运算符 (%),然后将 8 的余数减法添加到您的数字中。

public static void main(String[] args) {
    int i = 13;
    int rem = i % 8 > 0 ? i % 8 : 8;

    i += 8 - rem;

    System.out.println(i);
}

输出:16

【讨论】:

  • 感谢您的帮助。但是,如果我输入数字 8,它会四舍五入到 16。我怎样才能得到它,所以数字 8 将保持在 8 上而不是四舍五入到 16???
  • @user7327674 啊,我忘了检查i是否已经是8的倍数了。
  • @user7327674 我更新了我的答案,但它加入了一个条件,最好使用Mureinik's answerLouis Wasserman's answer
猜你喜欢
  • 1970-01-01
  • 2011-12-23
  • 1970-01-01
  • 2016-02-24
  • 1970-01-01
  • 2020-12-27
  • 2014-08-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多