My problem is specifically how to convert the float that the user gives (dollars), into an accurate integer (cents).
My code:
printf("O hai! How much change is owed?\n");
float change_owed = GetFloat();
(then a while loop if input is negative)
// convert float to int so can calc accurately
int cents_owed = change_owed * 100;
I know that this is incorrect, as for instance a user input of 4.2 gives a value of (4.2*100) as 419.999969, and therefore a value of cents_owed
of 419 (instead of 420).
I know that this is because of rounding errors inherent in floats; but I don't know how to covert the input float of 4.2 to an integer of 420. Help!
EDIT: After some googling I've found the roundf
function, which solves the problem. BUT..I'm pretty sure neither roundf
nor <math.h>
have been mentioned in the course so far. Have I used a shortcut here?
round()
orroundf()
function to turn the float into an integer. It was mentioned somewhere in the specification I think. Or maybe in the lecture.