gpt4 book ai didi

c++ - rand() 不工作,给我一个超出指定最大值和最小值的数字

转载 作者:太空宇宙 更新时间:2023-11-04 16:18:03 26 4
gpt4 key购买 nike

所以我正在制作一个游戏,如果你是老板和你雇用的员工,我以前使用过 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 将接收一个值的函数)尚未被调用。

关于c++ - rand() 不工作,给我一个超出指定最大值和最小值的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20319088/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com