rand()不起作用,给了我一个超出指定的最大值和最小值的数字

rand() not working, gives me a number outside of the specified max and minimum

本文关键字:数字 最小值 最大值 不起作用 rand 一个      更新时间:2023-10-16

所以我正在制作一个游戏,如果你是老板和雇佣员工,我以前使用过rand,但由于某种原因,它现在不起作用:

生成随机数的代码:

class employee
{
public:
int getSkills(int askingPrice)
    {
        srand((unsigned)time(0));
        switch(askingPrice)
        {
        case 1: //point of this is so if askingPrice is from 1 to 5 it will execute the same code
        case 2:
        case 3:
        case 4:
        case 5:
            skills = rand() % 5 + 1;
        }
        return skills;
    }
    int returnSkills()
    {
        return skills;
    }
    int getPaid(int askingPrice)
    {
        srand((unsigned)time(0));
        switch(askingPrice)
        {
        case 1:
        case 2:
        case 3:
        case 4:
        case 5:

            paid = rand() % 5 + 1;
        }
        return paid;
    }
    int returnPaid()
    {
        return paid;
    }
    int getHappy(int askingPrice)
    {
        srand((unsigned)time(0));
        switch(askingPrice)
        {
        case 1:
        case 2:
        case 3:
        case 4:
        case 5:

            happy = rand() % 5 + 1;
        }
        return happy;
    }
    int returnHappy()
    {
        return happy;
    }
private:
    int skills, paid, happy;
};

显示随机数的代码:

std::cout <<"Your first employee is: " << one.returnPaid() << " salary, " <<             one.returnSkills() << " skilled @ his job, " << one.returnHappy() << " happy with his job";

出于某种原因,它显示为:

Your first employee is: -858993460 salary, 3 killed @ his job, 3 happy with his job

为什么我的工资是负数,而其他什么都没有?

我正在使用Visual Studio 2010

当您调用one.returnPaid()时,one.paid尚未初始化,因为one.getPaid()one.paid将接收值的唯一函数)尚未被调用。