-
Rounding numbers
Ok I have everything coded out, but my rounding still doesn't work. According to the book (and the professor follows the book to the letter so if I don't do it like this thats about 50% off my grade) I'm supposed to convert a float number to integer and back to float to round, but common sense, as well as what I see after compile, tells me that just completely destroys the decimals. Heres the code. Anyone got any clue how to do this?
Code:
// Program by Aaron Friedley
// October 12, 2003
// Program rounds input then finds ceiling and floor
#include <iostream.h>
#include <math.h>
#include <iomanip.h>
int main (void)
{
// Prototypes
float round (void);
void ceilingfloor (float);
// Declarations
float num1;
// Calls
num1 = round ( );
ceilingfloor (num1);
return 0; // Terminate main
}
// *** round function ***
float round (void)
{
// Declarations
float num1;
int num2;
float num3;
cout << "Program by Aaron Friedley MWF 10:00\n\n"
<< "Input number: ";
cin >> num1;
// Declarations
num2 = num1;
num3 = num2;
cout << setiosflags(ios::fixed) << setiosflags(ios::showpoint)
<< setprecision(2) << "Rounded: " << num3;
return num3; // Terminate round
}
// *** ceilingfloor function ***
void ceilingfloor (float num1)
{
cout << "\nCeiling: " << ceil (num1)
<< "\nFloor: " << floor (num1) << "\n";
return; // Terminate ceilingfloor
}
-
Do you understand that rounding to the nearest integer is supposed to remove the decimal part? When you round a number to the nearest integer, you take the floor if its decimal part is less than .5 and the ceiling if its decimal part is greater than or equal to .5.
Your code inside of round() isn't really rounding, its taking the floor, since that is what happens when you convert from a float to an integer. To round a float by converting it to an integer the usual method is to add 0.5 to it first.
3.67 + 0.5 = 4.17 --> 4.00
2.26 + 0.5 = 2.76 --> 2.00
P.S. I am sorry that you take a class where the professor and/or book is out of date. For your own knowledge, <iostream.h>, <iomanip.h> and <math.h> should really be <iostream>, <iomanip> and <cmath>, and you can add using namespace std; on the line after the #includes so that you can use everything the same way.
-
The example the book gives is that 127.565031 rounds to 127.570000 so I don't know if that would be the way the program wants it done.
-
If the book wants you to use float to integer conversion as the way of rounding, then maybe you just need to multiply by 10^x where x is the number of digits after the decimal that will remain after rounding.
Sorry if I'm just giving you an answer, but how about:
127.565031 * 100 = 12756.503100
12756.5031 + 0.500000 = 12757.003100
int(12757.003100) = 12757
float(12757) = 12757.000000
12757.000000 / 100 = 127.570000
-
Thanks, just got out of class, talked to professor afterwards and she said that would be fine.