算术题


1. 定义整形变量,并且赋初值为0
2. 将四则运算符号储存在字符串数组中
3. 输入循环次数
4. 开始循环,再循环初始随机产生0和1,决定两种循环模式,并且设定好同一个循环变量
5. 若为0,在该模式中随机产生0-3一个数,判断产生的数是否为1若为1,在while循环中产生的两个数num1大于num2
6. 若为3,在while循环中判断num2不等于0
7. 其他随机产生两个数
8. 算式产生完毕,输出
9. 在第二种模式中,使用while循环判断num2和num4不等于0,随机产生四个数,输出结果。

遇到的问题:随机数函数rand产生的随机数每次运行结果是一样的。

原因:rand是伪随机数每次种子都是一样的。

解决问题:使用了srand((unsigned)time(NULL))根据时间改变随机种子。

#include <iostream>
#include <ctime>
#include <cmath>
#include <iomanip>
using namespace std;

int main()
{
    
    char ch[4]={'+','-','*','/'};
    srand((unsigned)time(NULL));
    int count;
    cout <<"请输入算术题的个数:";
    cin>>count;

    for(int i=0;i<count;i++)
    {
        
        int num1=0,
            num2=0,
            num3=0,
            num4=0;
        int choice=0;
        choice=rand()%2;
        if(choice==0)
        {
            int c;
            
            c=rand()%4;
        
            if(c==3)
            {
                while(num2==0)
                {
                    
                    num1=rand()%100;
                    num2=rand()%100;
                }
            }

            else
            {
                
                num1=rand()%100;
                num2=rand()%100;
            }

            cout <<setw(4)<<left<<num1<<" "<<ch[c]<<" "<<setw(4)<<left<<num2<<"="<<endl;
        }

        else
        {
            int c2;
            
            c2=rand()%4;
            while(num2==0||num4==0)
            {
                
                num1=rand()%100;
                num2=rand()%100;
                num3=rand()%100;
                num4=rand()%100;
            }
            cout <<num1<<"/"<<num2<<" "<<ch[c2]<<" "<<num3<<"/"<<num4<<" "<<"="<<endl;
        }
    }

    return 0;
}

运行结果

原文地址:https://www.cnblogs.com/dotacai/p/5251576.html