Help with rounding program

songweaver's Avatar, Join Date: Mar 2009
Newbie Member
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!
#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 shabbir; 4Mar2009 at 09:11.. Reason: Code blocks
xpi0t0s's Avatar, Join Date: Aug 2004
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.