-1

I need a while loop to only take in positive number. I wrote a while loop but it won't execute and Im not sure what's wrong. My code works fine with a for while loop but when I enter a negative number and run the code it prints out the input, then reprompts the user. I just want it to re-prompt, not print the input too.

Thank you if anyone can help.

This will print the input, then reprompt the user

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

int main(void)

{
    float change;

    do
    {
        change = get_float("Change: ");
        printf("%f\n", change);
    }
    while (change < 1);

}

This will not execute at all

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

int main(void)

{
    float change;

    while (change < 1)
    {
        change = get_float("Change: ");
        printf("%f\n", change);
    }


}
Steve Summit
  • 45,437
  • 7
  • 70
  • 103
Dkirch
  • 3
  • 2

2 Answers2

0

In the first one, just stop doing the printf inside the loop.

In the second one, you're testing the value of change before you store a value in it, which is Undefined Behavior.

0

Try below. check the comments for explanation

Using do..while loop

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

int main(void)

{
    float change;

    do
    {
        change = get_float("Change: ");

    }
    while (change < 1);
    printf("%f\n", change);

}

Using while loop

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

int main(void)

{
    float change;
    change = get_float("Change: "); //Capture value for first time
    while (change < 1) //Check if input value is negative
    {
        change = get_float("Change: "); //If negative ask for input again

    }

    printf("%f\n", change); // If value is positive, while loop passed over and value printed


}
Mudassir Hasan
  • 28,083
  • 20
  • 99
  • 133