1

I am trying to use the round function to go from dollars to cents, but I do believe there is something about round function I have misunderstood, because I just do not get the decimals with me when I multiply with 100 from the float to an int. This is the code in question

#include <stdio.h>
#include <cs50.h>
#include <math.h>

int main(void)
{
    int owed = 0;
    printf("Enter the owed amount: ");
    do {
         owed = GetFloat();
    } while (owed < 0);


    owed = owed * 100.0;
    float owe = roundf(owed);
    owe = (int)owe;
1
  • i wasn't know how to round it i was uding round() not roundf() could u explain it to me please – Ahmed Khaled Oct 12 '17 at 16:34
4

The main problem is how you are storing the initial retrieved value. You are calling GetFloat() and storing the result in owed, a variable of type int. GetFloat() returns a floating point number, which will be implicitly cast as an int when you try to store it in owed. In the process, the decimal point portion will be truncated. That means that you could try to store 4.85 all day and it will always store as integer 4.

You should store the value returned from GetFloat() in a float var, not an int. Later, multiply by 100 and round and then store it in an int, as you are trying to do.

As a side note, the last few lines, while they will work, aren't terribly clean. You create a new float to modify what should be another float and store the result, and on the next line, cast a float to an int and store the int back in a float. It would make more sense to round the float and store it back in the same float, but on the next line to cast the float as an int and store it in a new, int var. Or, a cleaner thing would be to do it all in one line: int change = roundf(dollars*100);

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

2
  • How could I miss that? Thank you so much. My code ended up looking terrible after 3 hours of tinkering around with the round function, I can't believe that I could make such a stupid mistake ;) – maxrimmer Jan 10 '16 at 9:57
  • This might be me just being super picky, but you should stay away from Implicit Casting and always use Explicit Casting it makes it much more obvious to the compiler as well as future programmers what you are trying to actually do. Its a very good habit to get into early in your programming as it will be second nature and save you alot of headaches (And make a lot better code). int change = (int)(roundf(dollars*100)); – Nick Young Jan 22 '16 at 15:22

You must log in to answer this question.

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