{
int i,j;
int key[2000];
srand((int)time(NULL));
printf("\nPlease Input A Number Bewteen 100 To 2000:");
start:
scanf("%d",&j);
if(j>=100 && j<=2000)
{
for(i=1;i<=j;i++)
{
key[i] = rand()%3000;
}
}
else
{
printf("\nError! \nPlease Input Again:");
goto start;
}
printf("\nCREATE COMPLETE !");
getch();
}
代码如上面,按理应该只能输入100至2000之间的整数,
可是,如果输入字母,就会出错,这是什么回事???
----------------解决方案--------------------------------------------------------
[CODE]
void create()
{
int i,j;
int key[2000];
srand((int)time(NULL));
while(1)
{
printf("\nPlease Input A Number Bewteen 100 To 2000:");
if(scanf("%d",&j)!=1) /* 输入字母重新输入 */
{
fflush(stdin);
continue;
}
if(j>=100 && j<=2000)
{
for(i=1;i<=j;i++)
{
key[i] = rand()%3000;
}
break;
}
else
printf("\nError! \nPlease Input Again:");
}
printf("\nCREATE COMPLETE !");
getch();
}
----------------解决方案--------------------------------------------------------
goto语句一般很少用的,以后尽量不要用
----------------解决方案--------------------------------------------------------
问题解决了,谢谢了
----------------解决方案--------------------------------------------------------
我也想到了一种方法,就是用getchar()来判别
具体如下:
# include <stdio.h>
# include <stdlib.h>
# include <conio.h>
# include <time.h>
# define MAXSIZE 2000
int error = 0;
main()
{
int i,j;
unsigned key[MAXSIZE];
srand((unsigned)time(NULL));
while(error==0){
printf("\nPlease Input A Number Bewteen 100 To 2000:");
scanf("%d",&j);
if(j==getchar()){
error = 1;
continue;
}
if(j >= 100 && j <= 2000){
for(i = 1;i <= j;i ++)key[i] =(int)(3000.0* rand()/(RAND_MAX+1.0));
break;
}
}
printf("\nPRESS ANY KEY CREATE NUMBERS !\n");
getch();
for(i = 1;i <= j;i ++){
printf("%5d",key[i]);
if(i%10 == 0)printf("\n");
}
printf("The RAND_MAX Is:%d",RAND_MAX);
printf("\nCREATE COMPLETE !");
getch();
}
----------------解决方案--------------------------------------------------------