所以我继续努力解决这个问题,我想出了这个解决方案:
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
//pre: stdlib.h and ctype.h needs to be included, input cannot be initialized to a value within low and high, low cannot be greater than high
//post: returns an integer value that ranges between low and high
int checkNumber(int input,int low,int high){
int noPass=0,check=input;
if(low>high){
printf("Low is greater than high, abort! \n");
exit(EXIT_FAILURE);
}
if(isdigit(check)){
noPass=1;
}
if((check<low)||(check>high)){
noPass=1;
}
if(noPass==1){
while(noPass==1){
printf("Input a number between %d - %d \n",low,high);
scanf("%d",&check);
getchar();
if((check>=low)&&(check<=high)){
noPass=0;
}
}
}
return check;
}
int main(int argc, char *argv[]){
int i=2147483647;
printf("Choose an alternative: \n");
printf("1. Happy Fun time! \n");
printf("2. Sad, sad time! \n");
printf("3. Indifference.. \n");
printf("4. Running out of ideas. \n");
printf("5. Placeholder \n");
printf("6. Hellow World? \n");
printf("0. -Quit- \n");
scanf("%d",&i);
getchar();
i=checkNumber(i,0,6);
if(i==0){
printf("You chose 0! \n");
}
if(i==1){
printf("You chose 1! \n");
}
if(i==2){
printf("You chose 2! \n");
}
if(i==3){
printf("You chose 3! \n");
}
if(i==4){
printf("You chose 4! \n");
}
if(i==5){
printf("You chose 5! \n");
}
if(i==6){
printf("You chose 6! \n");
}
return 0;
}
它按我想要的方式工作,但并不完美。最大的缺陷是 input ( int i
, in main()
) 中的值的变量无法初始化为介于低和高之间的值。例如:如果 int i=3; low=0 和 high=6,用户写一个字母:i 的值保持在 3。3 被发送到 checkNumber,并立即作为 3 传递。
我选择将 i 初始化为 2147483647,这是一个不太可能的数字 - 但它仍然是可能的。
结论:它有效,但有缺陷。