3

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?

3
  • No you are correct. You are supposed to use the round() or roundf() function to turn the float into an integer. It was mentioned somewhere in the specification I think. Or maybe in the lecture.
    – ChrisG
    Sep 22, 2015 at 15:08
  • Great, thanks. Sorry for the lack of research before posting - my first post - I'll do better next time!
    – andydavies
    Sep 22, 2015 at 15:12
  • round() or <math.h> was mentioned on pset1 in greedy part also in lecture video called greedy. you can check that out.
    – epic coder
    Sep 22, 2015 at 15:43

1 Answer 1

1

answered in my edit - confirmed by Chris G.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .