0

I'm testing the very first requirement of the Greedy assignment (ensure the input is not negative). I'm running into an issue where if I use < 0 in the while statement, -0.1, -0.2, -0.3 etc. is accepted. If I use <= any positive 0. values input e.g. 0.1, 0.2, 0.3 etc. are rejected. I've tried a number of things including using 0.00.

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

int main(void)

{

    int changeOwed;

    do
    {
        printf ("How much change is owed?\n");

        changeOwed = get_float();
    }
    while (changeOwed <= 0.00);

}

1 Answer 1

1

Well, let's think about what's happening. The code is changeOwed = get_float(); which is supposed to get a float and store it in changeOwed. However, changeOwed is declared as an int, not a float, so the number returned from get_float() is cast as an int.

In the process of casting a float as an int, the decimal or fractional part is truncated, not rounded, so any float between 0 and 1 is converted to 0. Then, the test condition comes into play. If the number is 0 or less, the loop repeats, so in effect, anything <1.0 will cause the loop to repeat.

BTW, is 0 defined as a positive, a negative, or neither? Is 0 considered a non-negative? Think about it. ;-)

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

1
  • Thanks for the explanation Cliff! Completely overlooked that I was declaring the variable as an integer. Commented Oct 4, 2017 at 9:36

You must log in to answer this question.

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