所以我正在制作一个游戏,如果你是老板和招聘员工,我之前使用过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
答案 0 :(得分:5)
当您致电one.returnPaid()
时,one.paid
尚未初始化,因为one.getPaid()
(one.paid
将收到某个值的唯一功能)尚未被调用。< / p>