标签:
目前对代码进行了些改动,将程序进行了一些封装,优化了一点代码。
由于之前的要求有所改动,先前是将题目从txt中读取,现在改成自动生成算式,存入txt中再进行读操作。
void create(){
srand((unsigned) time(NULL)); int len; int operate; int op0,op1,op2; int exibrac,brac1,brac2; char op; do{ len = rand() % 11; }while(len<=2); exibrac = rand() % 2;//0不存在,1存在括号 brac1 = rand() % (len-1); FILE *fp = fopen("test.txt","w+"); operate = len-1; op1 = rand() % 100; op0 = rand() % 2; if(len-operate==brac1 && exibrac == 1){ op = ‘(‘; fprintf(fp , "%c" , op ); brac2 = brac1 + 1 + rand() % (len-brac1-1); } if(op0==0){ fprintf(fp , "%d" ,op1); } else { fprintf(fp , "%d" ,op1); op=‘|‘; fprintf(fp , "%c" ,op); op1 = 2 + rand() % 98; fprintf(fp , "%d" ,op1); } while(operate>0){ op2=rand() % 4; switch(op2){ case 0: op = ‘+‘; break; case 1: op = ‘-‘; break; case 2: op = ‘*‘; break; case 3: op = ‘/‘; break; } operate--; fprintf(fp , "%c" , op ); if(len-operate==brac1 && exibrac == 1){ op = ‘(‘; fprintf(fp , "%c" , op ); brac2 = brac1 + 1 + rand() % (len-brac1-1); }//1+(2+3+4 op1 = rand() % 100; op0 = rand() % 2; if(op0==0){ fprintf(fp , "%d" ,op1); } else { fprintf(fp , "%d" ,op1); op=‘|‘; fprintf(fp , "%c" ,op); op1 = 2 + rand() % 98; fprintf(fp , "%d" ,op1); } if(len-operate==brac2){ op = ‘)‘; fprintf(fp , "%c" , op ); } } fclose(fp);}标签:
原文地址:http://www.cnblogs.com/13070037Yu/p/5348026.html