Go4Expert (http://www.go4expert.com/)
-   C++ (http://www.go4expert.com/forums/cpp/)
-   -   Help with rounding program (http://www.go4expert.com/forums/help-rounding-program-t16417/)

 songweaver 4Mar2009 02:59

Help with rounding program

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```

 xpi0t0s 4Mar2009 05:46

Re: Help with rounding program

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.

 All times are GMT +5.5. The time now is 11:09.