对随机生成的运算式进行计算,如果回答正确,加分,若错误,会扣分。答题失败后会给第二次机会答题,再失败则扣除对应分数并提示正确答案。并有答题时间统计。
下面是程序和说明(环境:VS2013)
project.h
#ifndef __PROJECT_H__
#define __PROJECT_H__
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
class pro
{
public:
int score = 0;
int cnt = 0;
void srandR(int a,int b);
void showResult();
private:
int m_a;
int m_b;
int m_c;
int m_value;
int m_Result;
};
#endif
project.cpp
#include "project.h"
void pro::showResult()
{
while (1)
{
cin >> m_value;
if (m_Result == m_value)
{
cout << "回答正确!" << endl;
score += 20;
break;
}
else
{
if (cnt == 0)
{
cout << "回答错误,请重新回答:";
score -= 10;
}
cnt++;
if (cnt == 2)
{
cout << "回答错误,答案是:" << m_Result << endl;
cnt = 0;
score -= 20;
break;
}
continue;
}
}//end for while
}
void pro::srandR(int a,int b)
{
m_a = a;
m_b = b;
srand((unsigned)time(NULL));
//产生1-4的随机数
m_c=rand() % 4 +1;
cout << m_c;
switch (m_c)
{
case 1:
m_Result = m_a + m_b;
cout << m_a << "+" << m_b <<"=";
break;
case 2:
m_Result = m_a - m_b;
cout << m_a << "-" << m_b << "=";
break;
case 3:
m_Result = m_a * m_b;
cout << m_a << "*" << m_b << "=";
break;
case 4:
m_Result = m_a / m_b;
cout << m_a << "/" << m_b << "=";
break;
default:
break;
}
showResult();
}
main.cpp
#include "project.h"
int main()
{
int begin_time, end_time , spendTime= 0;
pro p;
srand((unsigned)time(NULL));
begin_time = clock();
for (int i = 0; i < 5; i++)
{
cout << "第" << i + 1 << "题:";
//产生1-10的随机数
int a = rand() % 10 + 1;
int b = rand() % 10 + 1;
p.srandR(a, b);
}
end_time = clock();
spendTime = (end_time - begin_time) / CLOCKS_PER_SEC;
cout << "答题结束,你所获得的分数是:" << p.score << endl;
cout << "你所花费的时间是:" << spendTime <<"秒"<< endl;
return 0;
}
该项目还可以改善一下:如把分数和时间放入结构体中,再把每次获得结果的结构体对象存入结构体list中,重载 < 或者 > 运算符,可以实现多个玩家的分数比较,分数相同则比较时间长短。因此处涉及STL的容器算法,固不放在c++基础知识中讨论。