0

I am inputting 0.26 into cash.c, and after the first do while loop in my program, f = 0.00999999046

My second do while loop condition is f >= 0.10, yet it is executed even though f is less than that. Whats wrong?

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

int main(void)
{
    float f = get_float();
    int c = 0;
    do
    {
        f = f - 0.25;
        c++;
    }
    while (f >= 0.25);

    do
    {
        f = f - 0.10;
        c++;
    }
    while (f >= 0.10);

    do
    {
        f = f - 0.05;
        c++;
    }
    while (f >= 0.05);

    do
    {
        f = f - 0.01;
        c++;
    }
    while (f >= 0.01);

    printf("%i\n", c);

}

1 Answer 1

1

It's doing exactly what it was told. Remember the differences between a while loop and a do/while loop. A while loop can only execute if the condition is true because the test condition is checked BEFORE each pass. A do/while loop must execute at least once because the test condition is only checked AFTER each pass.

Maybe a review of the two types of loops is in order? ;-)

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

1
  • Hi, I was watching lecture 1 and lecture 1, continued late last night, and I am not remembering David talk much about while loops except maybe a very brief mention, and I'm not remembering him make that differentiation in either of the lectures. There was a decent amount of talk about do...while loops though. I will rewatch them and try to find the part where he mentions what you did. Thanks.
    – JohnWick
    Commented Feb 25, 2018 at 22:01

You must log in to answer this question.

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