计算需要将数字添加到坐标以更改下限值的次数

问题描述 投票:0回答:1

我有一个问题,需要我计算必须将数字添加到坐标x的次数,才能更改x的下限值。它必须同时支持正数和负数。

下面的示例代码突出了问题。

public static void main(String[] args) {
    double x = 10;
    double amountToAdd = -0.25; // must support positive+negative values
    int lastFlooredX = Integer.MIN_VALUE;
    int i = 0;

    while (i++ < 100) {
        int flooredX = (int) Math.floor(x);
        if (lastFlooredX == flooredX) {
            throw new UnsupportedOperationException("Iterated over the same number twice!");
        }
        lastFlooredX = flooredX;

        int additionsBeforeFloorChanges = // I need help!;

        x += (amountToAdd * additionsBeforeFloorChanges);
    }
}
java math
1个回答
0
投票

这样的事情?

public static int calc(double input, double amountToAdd) {
    if (input >= 0)
        return (int) Math.abs(Math.floor(input % 1 / amountToAdd));
    else
        return (int) Math.abs(Math.floor(input % 1 / amountToAdd - 1.0 / Math.abs(amountToAdd)));
}

一些示例(amountToAdd = -0.25):

  • 输入:10.6-输出:3
  • 输入:10.1-输出:1
  • 输入:10.0-输出:0
© www.soinside.com 2019 - 2024. All rights reserved.