随机实现100以内的的加减乘除运算

来源:互联网 发布:天翼飞young3.09 算法 编辑:程序博客网 时间:2024/05/23 01:15
算法思想:
(1) 产生两个随机数
(2) 产生一个运算符
(3) 用户输入答案
(4) 验证答案正确与否
(5) 转(1) 重复执行

主函数中用到了srand(time(NULL))上百度查了一下和随机产生有关。如果在程序运行时没有自主设置种子的话,用函数rand产生的随机数序列会是一样的。
而用srand设置随机数种子后,可能产生不同的随机序列(概率很大)。

int main(){    int number = 2;    int choice;    srand(time(NULL));    do    {        ShowMenu();        choice = getchar();        getchar(); //清除行尾回车        switch(choice)        {        case '1':        case '2':        case '3':        case '4':        case '5':            Arithmetic(choice,number);            break;        case '6':            cout<<"输入题目数:";            cin>>number;            getchar();        }    }    while(choice!='0');    return 0;}
主函数中调用了两个函数:菜单函数ShowMenu和四则运算函数Arithmetic。

菜单函数

void ShowMenu(){    cout<<"***********************"<<endl;    cout<<"*     1- 加法         *"<<endl;    cout<<"*     2- 减法         *"<<endl;    cout<<"*     3- 乘法         *"<<endl;    cout<<"*     4- 除法         *"<<endl;    cout<<"*     5- 混合运算     *"<<endl;    cout<<"*     6- 设置题目数   *"<<endl;    cout<<"*     0- 退出         *"<<endl;    cout<<"***********************"<<endl;}

四则运算函数中用了随机产生rand()%101。 rand()是随机取一个整数,再摸101,就是取余数。合起来的意思就是在0-100的范围内随机取一个整数。

运用循环控制题目次数。

void Arithmetic(int kind,int number){    int i;    int answer,result;    char str[80];    int score=0;    int operand1,operand2,operator1;    cout<<"四则运算,题目数:"<<number<<endl;    for(i=0; i<number; i++)//控制程序的题目数    {        operand1 =rand()%101;//产生1到100内的随机数        operand2 =rand()%101;        switch(kind)        {        case '1':            operator1=1;            break;        case '2':            operator1=2;            break;        case '3':            operator1=3;            break;        case '4':            operator1=4;            break;        default:            operator1=rand()%4+1;//operator1为1到5之间的随机数        }        switch(operator1)        {        case 1:            cout<<operand1<<"+"<<operand2<<"=";            result =operand1+operand2;            break;        case 2:            cout<<operand1<<"-"<<operand2<<"=";            result =operand1-operand2;            break;        case 3:            cout<<operand1<<"*"<<operand2<<"=";            result =operand1*operand2;            break;        case 4:            if(operand2==0) //注意除数为0operand2=1;operand1 = operand1 * operand2;            cout<<operand1<<"/"<<operand2<<"=";            result =operand1/operand2;        }        //cin>>answer;        cin.getline(str,80);        //answer = atoi(str);        sscanf(str,"%d",&answer);        if(answer==result)            score+=10;    }    cout<<"您的得分:"<<score<<endl;    cout<<"按任意键返回!";    getch();    cout<<endl;}

再加上相应的头文件

#include <iostream>#include <time.h>#include <stdlib.h>#include <conio.h>using namespace std;

就可以了。






0 0