我有一个问题,需要我计算必须将数字添加到坐标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);
}
}
这样的事情?
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