问题
I was trying to figure out what statement to use to get the user to enter a number between 1 and 10.
here is what i have so far.
int a;
printf("Enter a number between 1 and 10: \n);
scanf("%d", &a);
回答1:
int input;
while (true){
scanf("%d",&input);
if (input>=1 && input<=10){
// process with your input then use break to end the while loop
}
else{
printf("Wrong input! try Again.");
continue;
}
}
回答2:
Number beteween 1 to 10 right? so first stage you must validate if input is integer or not then you will check for range,
Below code is what i mention
#define MAX_RANGE 10
int input;
if (scanf("%d",&input) != 1)
{
printf ("Really bad input please enter integer number like in range 1 - 10\n");
}
Now in second stage as follows
if (input < 1 || input > MAX_RANGE) {
printf("It's an integer but out of range error\n");
}
You can also use while..loop
for same as follows
int input;
while (scanf("%d", &input) == 1 && input > 1 && input < 10)
{
// process your input
}
回答3:
Why not use the do .. while
loop?
int a;
do {
printf("Enter a number between 1 and 10: \n");
scanf("%d", &a);
} while (a < 1 || a > 10);
来源:https://stackoverflow.com/questions/21770397/how-to-prompt-the-user-to-enter-a-integer-within-a-certain-amount-of-numbers