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! 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
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.