我正在创建一台机器,它可以生成带有随机组件的霰弹枪,这些组件会影响枪的整体质量。我在生成构成霰弹枪的随机部件时遇到问题。必须生成 4 个部分。当我创建这些函数中的每一个时,我单独测试它们并且它们都可以工作,但是当我尝试将它们与createChromo()
函数组合在一起时,数字是单独随机的。我应该得到类似 2131 和 1332 的结果,但我不断得到 1111 或 1112 或 2221 或 2222 ......这是代码:
int generateButt()
{
srand(unsigned(time(NULL)));
int buttType = rand() % 3 + 1;
if(buttType == 1)
{
accuracy = rand() % ((5 - 2) + 2) / 10.0;
fireRate = fireRate - 0.3;
}
if(buttType == 2)
{
accuracy = rand() % ((8 + 5) + 5)/ 10.0;
fireRate = fireRate - 0.2;
}
if(buttType == 3)
{
accuracy = rand() % ((11 + 8) + 8) / 10.0;
fireRate = fireRate - 0.1;
}
return buttType;
}
int generateBarrel()
{
srand(unsigned(time(NULL)));
int barrelType = rand() % 3 + 1;
if(barrelType == 1)
{
range = rand() % (16 - 5) + 5;
power = power + 3;
}
if(barrelType == 2)
{
range = rand() % (21 - 16) + 16;
power = power + 1;
}
if(barrelType == 3)
{
range = rand() % (26 + 21) + 21;
power = power - 1;
}
return barrelType;
}
int generateBullet()
{
srand(unsigned(time(NULL)));
int bulletType = rand() % 3 + 1;
if(bulletType == 1)
{
power = rand() % (16 - 10) + 10;
range = range + 5;
}
if(bulletType == 2)
{
power = rand() % (26 - 16) + 16;
range = range + 1;
}
if(bulletType == 3)
{
power = rand() % (35 - 26) + 26;
range = range - 2;
}
return bulletType;
}
int generateAction()
{
srand(unsigned(time(NULL)));
int actionType = rand() % 2 + 1;
if(actionType == 1)
{
fireRate = 1.5;
accuracy = accuracy + 0.2;
}
if(actionType == 2)
{
fireRate = 2.0;
accuracy = accuracy - 0.1;
}
return actionType;
}
void createChromo(int a, int b, int c, int d)
{
cout <<a<<b<<c<<d<<"\n";
}
int main()
{
for(int i = 0; i < popSize; i++)
createChromo(generateButt(), generateBarrel(), generateBullet(), generateAction());
system("pause");
return 0;
}