如何将整数的输入限制为仅2-12? [英] How to limit an integer's input to 2-12 only?
问题描述
我想严格限制用户在此程序中输入的整数只能为2-12.我该怎么办?
I want to strictly limit a user's input on an integer in this program to 2-12 only. How do I do that?
#include <stdio.h>
int main(){
int i;
scanf("%d", &i);
int diceThrown, diceResult;
int sum = 0;
for(diceThrown = 1; diceThrown <= i; diceThrown++){
scanf("%d", &diceResult); //limit this input to 2-12 only, how?
sum += diceResult;
}
if(sum >= 40){
sum = sum % 40;
if(sum == 12){
printf ("28\n");
} else if(sum == 35){
printf ("7\n");
} else{
printf ("%d\n", sum);
}
} else if(sum < 40){
if(sum == 12){
printf ("28\n");
} else if(sum == 35){
printf ("7\n");
} else{
printf ("%d\n", sum);
}
}
return 0;
}
还要澄清一下,我仍然是编程的初学者(就像参加C.SCi课程只有两个月的时间一样),因此,如果您能像我这样解释我不是一个很好的专家,就可以对我进行解释. /p>
Also just to clarify, that I'm still a beginner in programming (like only 2 months into C.SCi course), so if you could explain it to me like I'm not a expert that would be great.
推荐答案
scanf
没有执行所需功能的功能.您可以只使用if
来验证输入.
scanf
has no functionality to do what you want. You can just use an if
to validate input.
if(scanf("%d", &diceResult) != 1 || diceResult < 2 || diceResult > 12) {
//handle invalid input here
}
如果输入无效,则取决于您要执行的操作.您可以忽略输入并要求用户输入有效的数字,可以退出整个程序或忽略错误,或者完全忽略其他内容.
If the input is invalid it is up to you what you want to do. You could ignore the input and ask the user to enter a valid number, you can quit the whole program or just ignore the error, or something else entirely.
您也可以使用while
反复检查输入:
You can also check the input repeatedly with an while
:
while(scanf("%d", &diceResult) != 1 || diceResult < 2 || diceResult > 12) {
//prompt user to enter valid input here
}
正如chux所提到的,处理无效输入的一部分是假定无效输入并检查EOF.
As mentioned by chux, part of handling invalid input would be to cosume the invalid input and check for EOF.
scanf("%d", &diceResult) != 1
将确保scanf实际上只读取一个数字,并且不会发生解析错误.
The
scanf("%d", &diceResult) != 1
will assure, that scanf actually read exactly one number and no parsing errors occurred.
这篇关于如何将整数的输入限制为仅2-12?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!