今天实现了如何利用C++的随机数自动出题,在这里需要注意的是,不管是字符还是整型数据,在if语句里面的判断均是
if( int1 == int2)
//or if( ch1 == 'A')
同时呢,这里还有将小写字母变大写的函数
toupper();
比如
#include <ctype.h>
char opera;
cout << "Please input operation:";
cin >> opera;
opera = toupper(opera);
cout << "opera = " << opera << endl;
上述就是在程序中需要注意的内容。
以下为源代码,我们下次再见啦!
#include <iostream>
#include <time.h>
#include <cstdlib>
#include <ctype.h>
using namespace std;
void Getrand(int,int &,int &);//声明获得随机数
void Putque(char,int &, int &);//声明输出算术题函数
int Calque(char, int ,int);//得到算术题结果
int main()
{
int grand;
int num1,num2;
char opera = ' ';
cout << "Please input your grand(1 or 2):";
cin >> grand;
cout << "Please input opera('a' or 's'):";
cin >> opera;
cout << endl;
opera = toupper(opera);
Getrand(grand,num1,num2);
Putque(opera,num1,num2);
int answer = Calque(opera,num1,num2);
int useranswer;
cin >> useranswer;//用户输入计算的答案
//将用户答案和正确答案进行比较
cout << "right answer is" <<'\t' << answer << endl;
if(useranswer == answer)
{cout << "You are right!" << endl;}
else
cout <<"You are wrong!" << endl;
}
void Getrand(int grand, int & num1,int & num2)
{ srand(time(NULL));
if(grand == 1)
{
num1 = 1 + rand() % 10;
num2 = 1 + rand() % 10;
}
else
{num1 = 1 + rand() % 100;
num2 = 2 + rand() % 100;
}
}
void Putque(char opera, int & num1,int & num2)
{ if(opera == 'A')
{ cout << num1 << '+' << num2 << "=" ;
}
else
{ if(num1 > num2)
{ cout << num1 << '-' << num2 << "=";
}else
{int temp;
temp = num1;
num1 = num2;
num2 = temp;
cout << num1 << '-' << num2 << "=" ;
}
}
}
int Calque(char opera, int num1,int num2)
{ int result;
if(opera == 'A')
{ result = num1 + num2;}
else
{result = num1 - num2;}
return result;
}