Help with rounding program

Discussion in 'C++' started by songweaver, Mar 3, 2009.

  1. songweaver

    songweaver New Member

    Joined:
    Mar 3, 2009
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    Below is the code which is supposed to round to two decimal places, i.e. 1.2874 is suppose to round to 1.29, but rather gives me 128.0000. What am I doing wrong need help fast! :confused:
    Code:
    #include <iomanip>
    #include <iostream>
    #include <cmath>
    using namespace std;
    
    double roundIt(double x, double n) 
    { 
        x = floor( x * pow(10.0, n) + 0.5 / pow(10.0, n));
        return x;
    }
    
    
    int main()                              
    {
        float x;
        
        cout << setprecision(4) << fixed << showpoint; 
        cout << "Enter number a positive number with a fractional part" << endl;
        cout << "more than 2 decimal places, i.e. 1.2574, to be" << endl;
        cout << "rounded to two deciaml places." << endl;
        cin >> x;
        
        cout << "The rounded answer for: " << x << "is: " << roundIt(x, 2)<< endl;
        
                                                                                                     
        cout << "\n\n\n\n";
        cout << "Jordan McGehee " << endl;
        cout << "Due 03-03-08 " << endl;
        
       
       
        system ("pause");
        
        
        return 0;                            
    }//end main
     
    Last edited by a moderator: Mar 4, 2009
  2. xpi0t0s

    xpi0t0s Mentor

    Joined:
    Aug 6, 2004
    Messages:
    3,009
    Likes Received:
    203
    Trophy Points:
    63
    Occupation:
    Senior Support Engineer
    Location:
    England
    Have another look at the precedence of operators and check if roundIt is really doing what you think.
    If it helps define some variables to various parts of the equation and make sure they're correct, e.g. double p1=pow(10.0, n), then replace pow(10.0, n) with p1.
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice