c do while loop doesn't work?
do
{
printf("Enter开发者_运维百科 number (0-6): ", "");
scanf("%d", &Num);
}while(Num >= 0 && Num <=6);
any ideas?
You're misunderstanding your loop.
Your code is read like this:
Do something While (as long as)
num
is more than (or equal to) zero Andnum
is less than (or equal to) six
The C compiler is listening to your code and doing exactly what you are (mistakenly) telling it to, which is to keep looping as long as the number is between 0 and 6.
You actually want it to keep looping as long as the number is not between 0 and 6, so you actually want the code to look like this:
Do something While
num
is less than zero Ornum
is more than six
Once the user enters a number that is between 0 and 6, the code will see that num
is neither less than 0 and nor more than 6, so it will stop the loop. (Because the condition will be false)
You should be able to code that yourself.
Hints: >
means 'more than', <
means 'less than', and ||
means 'or'.
It works completely fine for me, as long as Num
is declared as an int.
#include <stdio.h>
int main()
{
int Num;
do
{
printf("Enter number (0-6): ", "");
scanf("%d", &Num);
} while(Num >= 0 && Num <=6);
printf("Done.\n");
return 0;
}
Did you declare Num
as a char, perhaps?
@tom: Here's a sample session with my compiled code; what's different when you run it?
$ gcc a.c && ./a.out Enter number (0-6): 0 Enter number (0-6): 1 Enter number (0-6): 2 Enter number (0-6): 3 Enter number (0-6): 4 Enter number (0-6): 5 Enter number (0-6): 6 Enter number (0-6): 7 Done.
Maybe you need to add a getchar
after scanf
to remove '\n' from keyboard buffer:
do
{
printf("Enter number (0-6): ", "");
scanf("%d", &Num);
getchar();
} while(Num >= 0 && Num <=6);
Hope it helps.
This code is working fine with me, I have run your program, user can only enter the values from 0 to 6, do while work in this range, on other values loop break.
精彩评论