exiting a while loop with a negative integer

前端 未结 4 433
情话喂你
情话喂你 2021-01-27 13:15

I want to exit a while() when the user enters a negative number of any size. What kind of condition would I need at the start of the loop to get the loop to exit w

相关标签:
4条回答
  • 2021-01-27 13:51
    int i = -1;
    do
    {
        i = magic_user_input();
        //simple enough? get a decent programming book to get the hang of loops
    }
    while(i > -1)
    

    edit: sorry, my mistake: 'i' wasn't declared properly :) now it should be fine to use

    0 讨论(0)
  • 2021-01-27 13:52

    Use an if condition to know the number is less than 0 or not. And if yes, just use break statement inside it, which will bring you out of the loop. Learn more about break statement from MSDN.

    0 讨论(0)
  • 2021-01-27 14:02

    Well, what is a negative number? It's a number (call it x) that is less than zero, or symbolically, x < 0. If x is less than zero, then this is true. If not, then it is false.

    You can loop endlessly and break when this condition is met:

    while (1) {
      if (x < 0) {
        break;
      }
    
      ...
    }
    

    But I prefer to just use the opposite of that condition in the while loop itself:

     while (x >= 0) {
       ...
    

    While the condition is true, then the loop continues. When it is false (and your original condition is true, as these two are opposite), the loop breaks.

    0 讨论(0)
  • 2021-01-27 14:10

    Do not define your variable as unsigned variable. As suggested in other answers use if statement and break with if statement.

    example:

    int main(void)
    {
     int i;
     while(1){
     /*here write an statement to get and store value in i*/ 
      if(i<0)
      {
        break;
      }
     /*other statements*/
      return(0);
      }
     } 
    
    0 讨论(0)
提交回复
热议问题