Reputation: 33
trying to do something real simple but it's giving me a pretty big head ache.
I need to write a function that will round the value of a double argument to the number of decimal places specified by n.
I've gotten most of it down, but for some reason the result = ..... is only computing the first line of the rounding algorithm (see below)
The result is instead of rounding the number, it simply moves the decimal point the number of places specified by n. My code is below:
#include <iostream>
#include <cmath>
using namespace std;
double round(double x, int n)
{
double result;
result =
x * pow(10, n);
x = x + 0.5;
x = floor(x);
x = x / pow(10, n);
return result;
}
int main()
{
cout << round(-2.9, 0) << endl;
cout << round(-2.59, 1) << endl;
cout << round(.0059, 2) << endl;
cout << round(1.23467, 3) << endl;
cout << round(9.999999, 4) << endl;
return 0;
}
Upvotes: 0
Views: 3482
Reputation: 54806
You might get better results with something more like:
double round(double x, int n) {
x = x * pow(10, n);
x = x + 0.5;
x = floor(x) / pow(10, n);
return x;
}
The problem is that in the original code, you assign result = x * pow(10, n);
, but then proceed to perform all the rest of your operations using x
instead of result
.
You could also combine some of your statements to reduce the number of lines in your method, or even go for a one-liner like return floor(x * pow(10, n) + 0.5) / pow(10, n);
. Not that that's necessarily better, but when all you're doing is math, you don't need to perform each operation on its own line.
Upvotes: 1
Reputation: 25693
Your round()
returns result = x * pow(10, n)
, so what else did you expect?
Upvotes: 2