I have a formula of a sequence of double numbers k = a + d * n
, where a and d are constant double values, n is an integer number, k >= 0, a >= 0. For example:
..., 300, 301.6, 303.2, 304.8, 306.4, ...
I want to round a given number c
to a nearest value from this sequence which is lower than c
.
Currently I use something like this:
double someFunc(double c) {
static double a = 1;
static double d = 2;
int n = 0;
double a1 = a;
if (c >= a) {
while (a1 < c) {
a1 += d;
}
a1 -= d;
} else {
while (a1 > c) {
a1 -= d;
}
}
return a1;
}
Is it possible to do the same without these awful cycles? I ask because the following situation may appear:
abs(a - c) >> abs(d)
(the first number is much more then the second one and so a lot of iterations possible)
My question is similar to the following one. But in my case I also have a a
variable which has influence on the final result. It means that a sequence may haven't number 0.