|
I'm working on a program that rounds and adds two real numbers provided by the user. All is going well, except that one of my sample runs is producing an undesired result, and I can't figure out how to fix it for the life of me. The code itself is rather simple, but one problem just. Won't. Work.
1.674 + 1.322 produces:
1.67
1.32
---------
3.00
It should be producing 2.99! D: Please, any advice on how to get it to produce the desired output would be very, very much appreciated.
Here's the code, for your referrence. Sorry about any formatting issues.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
double a, b, sum;
cout << "Enter two real numbers to be rounded and added: ";
cin >> a >> b;
sum = a + b;
cout << endl << setw(30) << setiosflags(ios::fixed) << setprecision(2) << a << endl <<
setw(30) << b << endl << setw(30) << "---------" << setw(30) << endl << sum << endl;
return 0;
}
|
|
|
I tested ur code in Dev C++ and VC 6.0
with 1.674+1.322
It produced 2.996....i didn't find any rounding error
|
|
|
Did you, perhaps, set the precision as well? So it only shows two decimal places?
|
|
|
Sorry i didn't set the precision
But here's another way to round of the result and get the desired result
float RoundTwoDecimals( float num )
{
float result = (int)(num * 100.0) / 100.0;
return result;
}
Example
--------
2.996
(int)(2.996 * 100.0) / 100.0
(int)299.6 / 100.0
299 / 100.0
2.99
Tell me if it solves ur purpose...otherwise i'll try to give u some other solution
|
|
|
|
|
|
|
|