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

here's your problem:

x = floor( x * pow(10.0, n) + 0.5 / pow(10.0, n));
return x;

you forgot to divide x with 10^n after you finished rounding
and im not quite sure what is that 0.5 / pow (10.0, n) doing

and dont forget that putting tags such as reply quickly, fast, ASAP and so on wont help you solve the problem

I know that has to work, it was given to me exactly by my teacher, there must be something else wrong.

did you check if you wrote it the same way as your teacher said?
maybe you are missing some part of it.
(maybe teacher is wrong? XD joke)

do you have to use exactly the same algorithm as your teacher said, if not then try something like this:

int a = x*pow(10, n+1);
if ((a % 10) >= 5) a += 10- (a%10);
a = floor(a / pow(10, n+1));
return a;

I don't think there are any if statements in it.

You missed it by one closing parenthesis.

Your code:

x = floor( x * pow(10.0, n) + 0.5 / pow(10.0, n));

multiplies the number by a power of ten, then adds (.5 divided by that power of 10). That whole quantity is then passed to the floor( ) function. Thus you end up with a quantity that is just the original value multiplied by the power of ten, and truncated.

Remember your order of operator precedence.

The closing parenthesis needs to be after the addition of .5, so that you then divide by the power of ten, not by a very small number. Then apply the floor function. Like so:

x = floor( x * pow(10.0, n) + 0.5) / pow(10.0, n);

vmanes! You are greatness! Thanks!

I don't know about greatness, but I can be pretty good.

Next time you come visit us, please post your code inside the tags


your code goes here


That will make it easier for people to read. Enjoy!