2

Firstly, the syntax... if I have a float variable called 'change_owed', why do I need to write:

float roundf(float change_owed)

what's the purpose of these two floats I have to write?

Secondly, what does it actually mean by roundf?

Say change_owed = 4.02375, does it round every digit? Does it round it to the nearest int? Could someone round this number for me like the program would and tell me why it does it?

My impression was that you need to round the float before you multiply it by 100 in pset1?

0
4

The syntax you give (float roundf(float change_owed)) is what would be used for declaring the function roundf. That is, if you wanted to make a new function called roundf. But it's already defined in math.h. You just want to use it. The syntax you'd use for what I think you meant to be doing would look more like this:

First, declare a float variable

float change_owed;

then, you get the input from user, and store it in that variable just made. Then, round it

float rounded = roundf(change_owed)

...

As for what roundf() does precisely, type man roundf in the terminal to see the man page for that function, where what it does is explained (yes, it does round to the nearest integer: 4.02375, 4.123, and 4.45 would all be rounded to the float 4.0, but it's a good idea to actually read the man page, because you'll get all the information you need there).

In pset1, you want to round to an integer amount of cents. Say you're calling that int you get cents. So, if you have a float called dollars, which you want to round to the nearest cent, that's rounding to two decimal places. Since the function roundf() rounds to the nearest integer, not to two decimal places, in order to get the correct amount of cents, you need to multiply dollars by 100 before entering the dollar amount into the function. Then, since roundf() outputs a float, you'll need to "cast" the result as an int (know how to do that?).

4
  • Thanks - this syntax though: float rounded = roundf(change_owed). It looks like this is declaring a new variable called 'rounded' and setting that to the rounded change_owed? wouldn't it make more sense for it to say something like roundf(change_owed)? Thanks! – Elliot Byford Sep 11 '14 at 16:54
  • 1
    you are correct in your interpretation. float rounded = roundf(change_owed)declares a new variable called 'rounded' and setting that to the rounded change_owed. if you just run roundf(change_owed) you are not specifying anywhere to store the output. – postylem Sep 12 '14 at 5:22
  • Got you, so if wanted to store the output back into change_owed, could I type float change_owed = roundf(change_owed) - would that work? – Elliot Byford Sep 12 '14 at 23:04
  • 1
    then you would just write change_owed = roundf(change_owed) without the float, because the variable is already declared. – postylem Sep 13 '14 at 5:56

You must log in to answer this question.

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