How to use cmath function to round the nearest hundred

I am working on a project for class. I need to round a large number ex.((pi to 10 power)or(93650.237398) to the nearest hundred (93700). We need to use one of the cmath library functions to do this. I can not figure out which one to use. Can someone point me in the right direction
Last edited on
This should do it.
Basically, it removes the two last digits before it rounds, which makes it equivalent to rounding to the nearest 100. Then it multiplies by 100 to add the 00's back in.
Uncomment the other numbers to see if their results are to your liking.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// Example program
#include <iostream>
#include <string>
#include <cmath>

int main()
{
    const double Pi = 3.1; // fite me
    const double power = 10;
      
    // Test cases:
    double answer_unrounded = std::pow(Pi, power);
    //answer_unrounded = 54321.8765;
    //answer_unrounded = 54381.8765;
    //answer_unrounded = -54321.8765;
    //answer_unrounded = -54381.8765;
    
    std::cout << "Unrounded = " << answer_unrounded << std::endl;

    // http://www.cplusplus.com/reference/cmath/round/
    int answer_rounded = std::round(answer_unrounded / 100) * 100;

    std::cout << "Rounded   = " << answer_rounded << std::endl;
}


See also: http://www.cplusplus.com/forum/general/222965/

Edit: Simplified code using std::round
Last edited on
Topic archived. No new replies allowed.