新手c语言问题求助!!写一个程序帮助出数学题
帮小学生出题练习算数的程序,出十道题,加减乘除都有,要求结果在一百以内。问题:有的时候,程序运行中间会出现已停止工作的问题,求问怎么改进!!
程序代码:
#include <stdio.h> #include <ctype.h> #include <time.h> //#include <stdbool.h> #include <stdlib.h> #include <windows.h> #define IDNO_LENGTH 6 #define CALC_KIND 4 #define CALC_NUM 10 bool checkNo(char idNo[]); char getSignal(); int getResult(int,int,char); void takeTest(); //main函数 int main() { printf("Please input your four digit ID no(begin with two letters):"); char idNo[IDNO_LENGTH]; do { scanf("%s", idNo); //fflush(stdin); } while(checkNo(idNo) == false); printf("1.Start a test\t2.Check score\t3.Exitb\n"); int choose; do { printf("选择:"); scanf("%d", &choose); //fflush(stdin); } while(choose != 1 && choose !=2 && choose!=3); if(choose==1) { takeTest(); }else if(choose==2) { FILE *fp; int ch; if((fp=fopen("score.txt","r+"))==NULL) { printf("\n你还没做过题目测试"); getchar(); exit(1); } ch = fgetc(fp); while(ch!=EOF) { putchar(ch); ch = fgetc(fp); } fclose(fp); } else { exit(0); } return 0; } //获取随机运算符 char getSignal() { char signal[CALC_KIND]={'+','-','*','/'}; srand((unsigned)time(NULL)); return signal[rand()%4]; } //获取随机数 int get_random(void) { int i; i=rand() % 100; return (i); } //运算 int getResult(int num1,int num2,char signal) { float res; switch(signal) { case '+': res=num1+num2;break; case '-': res=num1-num2;break; case '*': res=num1*num2;break; case '/': res=num1/num2;break; default: res=0; printf("运算符不符合规则\n"); } return res; } //int checkresult(int h) //{ // float res; // res=getresult(num1,num2,signal); // if (int(res)!=res|res>=100) h=0; // else h=1; // return h; //} //列出10道题 void takeTest() { printf("开始答题,每道题10分,总共100分\n"); clock_t startTime; startTime=clock(); int index; int res; int giveRes; int l,k,h; int num1; int num2; int score=0; char signal; for(index=0;index<CALC_NUM;index++) { signal=getSignal(); srand((unsigned)time(NULL)); if(signal=='+'||signal=='-') { num1=get_random(); num2=rand()%(100-num1); } if(signal=='-') { num1=get_random(); num2=rand()%num1; } res=getResult(num1,num2,signal); if(res>100||res<0) k=0; else k=1; if(signal=='*') { num1=get_random(); num2=rand()%(100/num1); } if(signal=='/') { do { num1=get_random(); num2=rand() % num1; while(num2==0) num2=rand() % num1; int c; c=num1/num2; if(num2*c==num1) h=1; else h=0; }while(h==0); } printf("%d%c%d=",num1,signal,num2); scanf("%d", &giveRes); //fflush(stdin); if(getResult(num1,num2,signal)==giveRes) { printf("correct\n"); score+=10; } else { printf("wrong\n"); } } FILE *fp=fopen("score.txt","w"); fprintf(fp,"分数为%d",score); fclose(fp); printf("解10道题用了%lf秒\n",(double)(clock()- startTime)/CLOCKS_PER_SEC); } //检测idNo是否合规则,合规则返回true bool checkNo(char idNo[]) { int index; bool flag; flag=true; for(index=0;index<IDNO_LENGTH;index++) { if(index<2) { if(!isalpha(idNo[index])) { flag=false; printf("ID no 不符合规则,重新输入:"); break; } } else { if(!isdigit(idNo[index])) { flag=false; printf("ID no 不符合规则,重新输入:"); break; } } } return flag; }