问题
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 when the user enters a negative number?
回答1:
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.
回答2:
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.
回答3:
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
回答4:
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);
}
}
来源:https://stackoverflow.com/questions/7761525/exiting-a-while-loop-with-a-negative-integer