关于程序的输入数值的合法性判断,请教
程序代码:
//求最大公约数 //1.辗转相除法 //2.更相减损术 //要求:采用模块化思想编写程序,程序中要求使用两种方法实现求最大公约数 // 并且在程序界面能让用户选择使用何种方法。 #include <stdio.h> int Zhanzhuan (int a,int b); int Gengxiang (int a,int b); int main() { int a; int b = -1; int c = -1; int result; int ret; printf("Zhan zhuan xiang chu fa:1\nGeng xiang jian sun shu:2\n Please input:"); while(1) //对于输入数据的合法性判断 { ret = scanf("%d",&a); if(a != 1 && a != 2) printf("Wrong! Please input number 1 or 2 again.\n"); do { while(ret != 1) { getchar(); } ret = scanf("%d",&a); }while(ret != 1); if(a == 1 || a == 2)break; } printf("Please input two numbers you want (for example 11,12): "); do { scanf("%d,%d",&b,&c); if( b <=0 || c <= 0) printf("Wrong! input again: "); }while( b <=0 || c <= 0); if(a == 2) result = Gengxiang(b,c); if(a == 1) result = Zhanzhuan(b,c); printf("the biggest Common divisor is %d\n",result); return 0; } //辗转相除法 int Zhanzhuan (int a,int b) { int c; int temp; if(b > a) { temp = a; a = b; b = temp; } if(a == b) { return a; } do { c = a % b; if(c != 0) { a = b; b = c; } }while(c != 0); return b; } //更相减损术 int Gengxiang (int a,int b) { if(a == b) return a; while(a != b) { if(a > b) a-=b; else b-=a; } return a; }里面的这一部分
while(1) //对于输入数据的合法性判断
{
ret = scanf("%d",&a);
if(a != 1 && a != 2)
printf("Wrong! Please input number 1 or 2 again.\n");
do
{
while(ret != 1)
{
getchar();
}
ret = scanf("%d",&a);
}while(ret != 1);
if(a == 1 || a == 2)break;
}
我的原意是想在输入数据时候不仅能判断是否a=1或a=2,如果输入逗号,空格什么的都能识别并且重新输入数据
但是运行程序时候,后面的程序不能运行,这是怎么回事?
还有我想请教下,怎么写这段程序,既能够判断数字是否符合要求,又能判断输入错误的符号,逗号什么的?