上面是不是有四种编法来的?
定义在"calculate.h"中。 #include <iostream> #include <ctime> #include <cstdlib> #include <cmath> using namespace std;
class Calculate { private: int level; //计算级别。 char type; //计算类型。 //参与计算的参数1,参数2, 计算结果,统计正确个数,统计错误个数。统计个数的变量如果用int型,计算结果都是0,取整了! float parameter1, parameter2, numofcorrect, numoffalse; double answer; public: Calculate(); void Stat(); //统计计算的结果. void GetParameter(int Level); //取得参与计算的参数 void Addition(); //加 void Subtration(); //减 void Multiplication(); //乘 void Division(); //除 inline IncNumOfCo(){ numofcorrect +=1; cout<<"RIGHT!"<<endl;} inline IncNumOffa(){ numoffalse +=1; cout<<"WRONG!"<<endl;} inline Judge() { char temp; cout<<"继续练习? y\\n "; cin>>temp; if ((temp != 'n')&&(temp !='y')) exit(1); else if(temp == 'n') Stat(); } }; Calculate::Calculate() { numofcorrect = numoffalse = answer = parameter1 = parameter2 = 0.0; level = 0; type=' '; cout<<"请选择计算类型(加法 + 减法 - 乘法 * 除法 / 否则退出):"; cin>>type; switch(type) { case '+': Addition(); case '-': Subtration(); case '*': Multiplication(); case '/': Division(); default: cout<<"在选择运算类型上出现错误!请重新运行程序!"; cout<<endl; exit(1); } } void Calculate::Addition() { cout<<"请输入运算级别(1,2 3):"; cin>>level; while(1) { GetParameter(level); cout<<parameter1<< type <<parameter2<<"="; cin>>answer; if(answer == parameter1+parameter2) IncNumOfCo(); //答案正确,numofcorrect加1; else IncNumOffa(); //答案错误,numoffalse 加1; Judge(); //判断是否继续练习! } } void Calculate::Subtration() { cout<<"请输入运算级别(1,2 3):"; cin>>level; while(1) { GetParameter(level); cout<<parameter1<< type <<parameter2<<"="; cin>>answer; if(answer == parameter1-parameter2) IncNumOfCo(); else IncNumOffa(); Judge(); } } void Calculate::Multiplication() { cout<<"请输入运算级别(1,2 3):"; cin>>level; while(1) { GetParameter(level); cout<<parameter1<< type <<parameter2<<"="; cin>>answer; if(answer == parameter1*parameter2) IncNumOfCo(); else IncNumOffa(); Judge(); } }
void Calculate::Division() { cout<<"请输入运算级别(1,2 3):"; cin>>level; while(1) { GetParameter(level); if(parameter2 == 0) //除数如果是0,重新取数! continue; cout<<parameter1<< type <<parameter2<<"="; cin>>answer; if( fabs(answer-parameter1/parameter2)<0.001 ) //有个缺陷: IncNumOfCo(); else IncNumOffa(); Judge(); } } void Calculate::GetParameter(int Level) { srand( (unsigned)time(NULL) );
switch (Level) { case 1: parameter1 = rand() %10; parameter2 = rand() %10; break; case 2: parameter1 = rand() %50; parameter2 = rand() %50; break; case 3: parameter1 = rand() %100; parameter2 = rand() %100; break; default: cout<<"在选择运算级别上出现错误!请重新运行程序!"; cout<<endl; exit(1); //退出程序 } } void Calculate::Stat() { cout<<"您计算的正确率是:"<<numofcorrect/(numofcorrect+numoffalse)<<" 下次继续努力!"<<endl; exit(1); } #include "calculate.h"
int _tmain(int argc, _TCHAR* argv[]) { Calculate a; return 0; }