0

I think I have figured out a way to convert the users input from dollars to cents. I used the eprintf function and it works. However, when re-watching Zamyla's walk through she mentions towards the end of the conversion section that we need to be careful about floating point imprecision and the output needs to be rounded off. So, I ran an unrealistic value of 1.039 and expected to get 104 but instead got 103. I browsed through Lecture 1 and couldn't find where he covered rounding, though I might have glanced over it. I did find where he talked about changing floating points though.

How do I get the program to round correctly?

//Program to give the most efficient amount of coins when returning change
#include <stdio.h>
#include <cs50.h>

//Prompt user for a positive dollar amount

int main(void)
{
    float dollars;
    do
    {
        dollars = get_float("Enter dollar amount:");
    }
    while(dollars<0);

    //convert dollars to cents

    int cents;
    {
        cents = (dollars * 100);
        eprintf("%i\n", cents);
    }
 }

result that is not rounded correctly

1 Answer 1

0

Conversion from floating point to integer truncates the value, rounding towards zero. So even if your value dollars * 100 were something like 103.9999, the result of the conversion would still be 103.

You can avoid this by rounding.

There is a round function in math.h (the library comes with the compiler, but is not considered core, so the linker needs -lm just as it needs -lcs50 for the cs50 library).

But as we know the value is positive, we could simply add 0.5 before the conversion to integer. For an original value with a fractional part between .0 and .4999..., it would still be rounded down, but a value of .5 and up would result in the next integer.

You must log in to answer this question.

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