0

I don't know if the following idea is feasible or not to generalize it, but I want to round every calculated value to the 100 unit rounding up.

example:

double x;
int x_final;
...
if (x<400) x_final=400;
else if (x<500) x_final=500;
else if (x<600) x_final=600;
...
4

4 回答 4

2

为了四舍五入,你可以使用这个:

x_final = ((int)x / 100 + 1) * 100;
于 2013-10-10T08:37:33.987 回答
1

The obvious solution is to use remquo:

int
roundTo100( double x )
{
    int results;
    remquo( x, 100.0, &results );
    return 100 * results;
}

You'll probably need a fairly recent compiler for this, however: the function was added to C99, and to C++ with C++11. Depending on the platform, you might not have it at all, or you might only have it in <math.h> (but not in <cmath>). If the compiler claims C++11 support, you should have it in <cmath>. But don't believe it until you've seen it; no compiler actually supports C++11 to any real degree yet. On platforms where there is support for C99 (which would include pretty much all Unix platforms, and CygWin under Windows), it should be present in <math.h>, regardless. (But it is not present in Visual Studios.)

In the absense of this function, something like:

int
roundTo100( double x )
{
    int results = round( x / 100 );
    return 100 * results;
}

might do the trick. Beware that the two functions round slightly differently. The first is rounds up if the remainder is exactly 50, the second is round to even. The second may potentially introduce inaccuracies due to the division (or not—I've not analysed it sufficiently to be sure one way or the other).

Depending on where your x comes from, the rounding differences or the potential inaccuracies may not be an issue. (If, for example, the x is derived from some physical measurements with only 3 decimal digits accuracy, the fact that it may round "incorrectly" when x is distant from 50 by some 1E14 or the like is probably irrelevant.)

于 2013-10-10T09:02:11.400 回答
0

试试这个:

#include <math.h>
...

x_final = ceil(x/100)*100;
于 2013-10-10T08:39:25.437 回答
0

将其除以 100(忽略余数),然后乘以 100。

#include <iostream>
using namespace std;

int main() {
    int val = 456;
    int r = (val / 100) * 100;
    cout << "r = " << r;
    return 0;
}
于 2013-10-10T09:15:17.250 回答