class Question{
protected:
int op1;
int op2;
string operate;
public:
Question();
};
class generateRandomQuiz:Question{
public:
generateRandomQuiz();
int getp1();
int getp2();
string getOp();
};
class checkAnswer:generateRandomQuiz{
private:
int Ans;
public:
checkAnswer(int ans);
};
Question::Question()
{
op1=23;
op2=12;
operate="/";
}
generateRandomQuiz::generateRandomQuiz():Question()
{
op1=rand()%50;
op2=rand()%50;
string s="+-/*";
int n=rand()%4;
operate=s[n];
}
int generateRandomQuiz::getp1()
{
return op1;
}
int generateRandomQuiz::getp2()
{
return op2;
}
string generateRandomQuiz::getOp()
{
return operate;
}
checkAnswer::checkAnswer(int ans):generateRandomQuiz()
{
Ans=ans;
string operate=getOp();
int op1=getp1();
int op2=getp2();
if (operate=="+")
{
if (op1+op2==Ans)
{
cout<<"Your answer is correct."<<endl;
}
else
{
cout<<"You can do better next time."<<endl;
}
}
if (operate=="-")
{
if (op1-op2==Ans)
{
cout<<"Your answer is correct."<<endl;
}
else
{
cout<<"You can do better next time."<<endl;
}
}
if (operate=="*")
{
if (op1*op2==Ans)
{
cout<<"Your answer is correct."<<endl;
}
else
{
cout<<"You can do better next time."<<endl;
}
}if (operate=="/")
{
if (op1/op2==Ans)
{
cout<<"Your answer is correct."<<endl;
}
else
{
cout<<"You can do better next time."<<endl;
}
}
}
int main()
{
cout<<"This quiz is about evaluating an expression which is being generatedrandomly"
<<endl;
generateRandomQuiz Q;
int answer;
int op1=Q.getp1();
int op2=Q.getp2();
string opr=Q.getOp();
cout<<"What is: "<<op1<<op2<<op2<<"=?"<<endl;
cin>>answer;
checkAnswer A(answer);
system("PAUSE");
return 0;
}我正在编写一个程序,它随机生成一个测验,并要求用户提供如下答案:什么是: 15 / 43 =?当我给出正确的答案时,运算符和数字是随机的generated.But,即使是错误答案的注释也会打印出来。我写的条件很好,有人能指出一下吗?谢谢
发布于 2012-12-16 20:17:31
要检查答案,您需要依赖于checkAnswer 继承自 generateRandomQuiz这一事实。
但是,当您实际检查答案时,您使用的是与随机生成的测验不同的实例,因此您无法通过执行类似int op1=getp1();的操作来获得生成的测验。
所以检查机制是正确的,它只是检查一个不同的问题。我建议你重新考虑你的代码结构,它看起来非常笨拙。
https://stackoverflow.com/questions/13900885
复制相似问题