📄 quiz.cpp
字号:
#include <iostream>
#include <string>
using namespace std;
#include "mathquest.h"
#include "prompt.h"
// quiz program for illustrating class design and implementation
class Student
{
public:
Student(const string& name); // student has a name
int Score() const; // # correct
string Name() const; // name of student
bool RespondTo(Question & q); // answer a question, update stats
private:
string myName; // my name
int myCorrect; // my # correct responses
};
Student::Student(const string& name)
: myName(name),
myCorrect(0)
{
// initializer list does the work
}
bool Student::RespondTo(Question & q)
// postcondition: q is asked, state updated to reflect responses
// return true iff question answered correctly
{
string answer;
q.Ask();
cin >> answer;
if (q.IsCorrect(answer))
{ myCorrect++;
cout << "yes, that's correct" << endl;
return true;
}
else
{ cout << "no, that's not correct" << endl;
return false;
}
}
int Student::Score() const
// postcondition: returns # correct
{
return myCorrect;
}
string Student::Name() const
// postcondition: returns name of student
{
return myName;
}
class Quiz
{
public:
Quiz();
void GiveQuestionTo(Student & s); // ask student a question
private:
Question myQuestion; // question generator
};
Quiz::Quiz()
: myQuestion()
{
// nothing to do here
}
void Quiz::GiveQuestionTo(Student & s)
// postcondition: student s asked a question
{
cout << endl << "Ok, " << s.Name() << " it's your turn" << endl;
cout << "type answer after question " << endl;
myQuestion.Create();
if (! s.RespondTo(myQuestion))
{ cout << "try one more time" << endl;
if (! s.RespondTo(myQuestion))
{ cout << "correct answer is " << myQuestion.Answer() << endl;
}
}
}
int main()
{
Student owen("Owen");
Student susan("Susan");
Quiz q;
int qNum = PromptRange("how many questions: ",1,5);
int k;
for(k=0; k < qNum; k++)
{ q.GiveQuestionTo(owen);
q.GiveQuestionTo(susan);
}
cout << owen.Name() << " score:\t" << owen.Score()
<< " out of " << qNum
<< " = " << double(owen.Score())/qNum * 100 << "%" << endl;
cout << susan.Name() << " score:\t" << susan.Score()
<< " out of " << qNum
<< " = " << double(susan.Score())/qNum * 100 << "%" << endl;
return 0;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -