PDA

View Full Version : rounding whole numbers in C++


drumminfool91
11-07-2009, 06:17 PM
I am ABSOLUTELY brand new to C++ and have a question about rounding numbers.
What I need to do is make a program that determines whether or not a number is a multiple of 1000, and if not to automatically round the number up to the next highest multiple of 1000 (i.e. if the number is 579, then it would need to be rounded to 1000; if the number is 3568, it needs to be rounded to 4000, etc...). This needs to be done in a user-defined function and returned to the main. Here's what I have so far:

#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;

double RoundingFunction (double nonrounded_number)
{
double rounded_number


if (nonrounded_number % 1000 == 0)
then return (nonrounded_number);
else
rounded_number = nonrounded_number + 1000;
}

int main ()
*/ rest of program /*

--------------------------------------------------------

I know adding 1000 won't do the trick, but I'm not sure what to use... is it the ceil(x) function? If so, what would that look like?

oracleguy
11-08-2009, 01:09 AM
Have it print out the result of 1000 - nonrounded_number % 1000 and you'll see what you need to add.

gtguy87
11-09-2009, 12:56 PM
I am ABSOLUTELY brand new to C++ and have a question about rounding numbers.
What I need to do is make a program that determines whether or not a number is a multiple of 1000, and if not to automatically round the number up to the next highest multiple of 1000 (i.e. if the number is 579, then it would need to be rounded to 1000; if the number is 3568, it needs to be rounded to 4000, etc...). This needs to be done in a user-defined function and returned to the main. Here's what I have so far:

#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;

double RoundingFunction (double nonrounded_number)
{
double rounded_number


if (nonrounded_number % 1000 == 0)
then return (nonrounded_number);
else
rounded_number = nonrounded_number + 1000;
}

int main ()
*/ rest of program /*

--------------------------------------------------------

I know adding 1000 won't do the trick, but I'm not sure what to use... is it the ceil(x) function? If so, what would that look like?

#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;

double RoundingFunction (double nonrounded_number)
{
return ceil(nonrounded_number/1000)*1000;
}

int main ()
*/ rest of program /*