I've said this many times before, floats are approximations and dealing with that takes a lot of care and attention.
Some code and output to munch on
Code:
#include <iostream>
#include <iomanip>
using namespace std;
void example1(void)
{
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;
}
double roundto2dp ( double a ) {
int temp = (int)( a * 100.0 );
return temp / 100.0;
}
void example2(void)
{
double a, b, sum;
cout << "Enter two real numbers to be rounded and added: ";
cin >> a >> b;
cout << "Actual values " << setprecision(20) << a << " " << b << endl;
a = roundto2dp(a);
b = roundto2dp(b);
sum = a + b;
cout << "Actual values " << setprecision(20) << a << " " << b << " " << sum << endl;
cout << endl << setw(30) << setiosflags(ios::fixed) << setprecision(2) << a << endl <<
setw(30) << b << endl << setw(30) << "---------" << setw(30) << endl << sum << endl;
}
int main ( ) {
example1();
example2();
return 0;
}
$ g++ foo.cpp
$ ./a.out
Enter two real numbers to be rounded and added: 1.674 1.322
1.67
1.32
---------
3.00
Enter two real numbers to be rounded and added: 1.674 1.322
Actual values 1.67399999999999993250 1.32200000000000006395
Actual values 1.66999999999999992895 1.32000000000000006217 2.99000000000000021316
1.67
1.32
---------
2.99
Doubles have about 15 decimal digits of precision, so the last 5 or so digits in each of the actual results are just noise.