有加减和乘法3种运算,由于除法涉及到浮点数存储有误差,所以比较难实现,改程序还有判定分数机制,根据难度给定合适的分数,随机抽取运算题目和符号。下面的代码适合Linux和安卓上的编译器,因为用了ANSI转义字符\033[3xm,其中x是0到7的数字表示颜色,如果电脑也想用那么只需删除这个即可。
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
enum sig {ADD,SUB,MUL
};
int main()
{int C;int guess,a,b,res,score=0,sig=0,level,arr[4]= {700/C,1000/C,1600/C,2800/C};struct timeval start, end;char* sigstr[3]= {"+","-","×"};float pass_time;printf("测试心算能力,请所有运算都靠在脑海中完成,时间越快分值越高\n请输入题目数量(1道以上)");scanf("%d",&C);srand(time(0));for(int i=0; i<C; i++){sig=rand()%3;if(sig==DEV) {a=rand()%90+10;b=rand()%90+10;res=a*b;int moda=a%10,modb=b%10;if(a<20||b<20||moda==0||modb==0)//十位为1或是整十数视为简单level=2;else if(moda>4&&moda<9&&modb>4&&modb<9||a/10>6&&b/10>6)//数字比较大并且不整十level=4;else level=3;}else {a=rand()%9000+1000;b=rand()%9000+1000;if(sig==ADD)res=a+b;else res=a-b;level=1;}printf("\033[36m%d%s%d=",a,sigstr[sig],b);gettimeofday( &start, NULL );scanf("%d",&guess);gettimeofday( &end, NULL );pass_time=(end.tv_sec - start.tv_sec) + (end.tv_usec - start.tv_usec)/1000000.0;if(guess==res){printf("\033[32m答对了!,花费时间%.2f秒\n",pass_time);float tmp=arr[level]/pass_time;if(tmp>150/C)tmp=150/C;//如果单道题目用时太短导致分数过高那么取值为上限score+=tmp;}else printf("\033[31m错了,正确答案为%d,再接再厉\n",res,pass_time);}if(score>100)score=100;printf("你的分数为%d",score);
}