如何检测用户输入int是否介于两个数字之间?
我试过这样做:
int x=3;
printf("Enter the size of the triangle: ");
scanf("%d", &size);
odd=size%2;
for(x=3;x<21;x++)
{
if(x==size&&odd==1)
{
break;
}
else
{
printf("The size must be an odd number and be between\n3 and 21, inclusive, please try again\n\n");
printf("Enter the size of the triangle: ");
scanf("%d",&size);
odd=size%2;
x=3;
}
}
但我唯一可以使用的输入是3。
答案 0 :(得分:3)
您已经在代码中拥有了解决方案的所有内容:
if (size >= 3 && size <= 21) {
// size is between 3 and 21 inclusive
} else {
// size is less than 3 or more than 21
}
如果您还想确保它是奇数,您可以添加条件:
if ((size >= 3) && (size <= 21) && (size % 2 == 1)) {
// size is between 3 and 21 inclusive, and odd
} else {
// size is less than 3 or more than 21 or even
}
答案 1 :(得分:1)
如果您需要不断询问用户输入的号码,直到他们输入以下号码:
你可以使用类似的东西:
printf ("Enter the size of the triangle: ");
scanf ("%d", &size);
while ((x < 3) || (x > 21) || (x % 2 == 0)) {
printf ("The size must be an odd number and be between\n"
"3 and 21, inclusive, please try again.\n\n");
printf ("Enter the size of the triangle: ");
scanf ("%d", &size);
}
这可能是最简单的形式。它得到数字然后进入while
循环,直到它有效。
你可以将printf/scanf
对重构为一个单独的函数,但在这样的小片段中这可能不那么重要。
答案 2 :(得分:0)
怎么样:
if(x >= 3 && x <= 21 && x%2) {
...
}
答案 3 :(得分:0)
printf("Enter the size of the triangle");
scanf("%d", &size);
if (3 <= size && size <= 21 && size % 2) {
// size is between 3 and 21 (inclusive) and odd
}