伙计们,当我运行它时,我的程序出现了这个非常奇怪的错误。这是重要的代码:
变量(编辑):
const short int maxX = 100;
const short int maxZ = 100;
const short int lakeChance = 0.9;
addLake函数(编辑):
void addLake(Sect sector[][maxZ], int x, int z){
sector[x][z].setMaterial(1);
}
主要来源(编辑):
//Generating land mass
for (int x = 0; x < maxX; x++){
for (int z = 0; z < maxZ; z++){
//Default material
sector[x][z].setMaterial(0);
//Add lake/sea source
int r = rand();
float r1 = (r % 1000);
float r2 = r1 / 1000;
if (r2 <= lakeChance) addLake(sector, x, z);
}
}
错误在于,无论我改变'lakeChance'值,结果似乎完全相同。因为addLake函数似乎每次启动时调用大约3到6次,尽管我更改了lakeChance的值更高(即:0.5,0.7,0.9)。只有当我将'lakeChance'的值更改为1时,才会调用该函数。随机数生成器工作正常,因此结果每次都会有所不同。
答案 0 :(得分:4)
我看不出任何显然错误本身。所以我尝试了下面的代码:
int test(float chance)
{
int call = 0;
for(int i = 0; i != 100000; i++)
{
int r = rand();
float r1 = (r % 1000);
float r2 = r1 / 1000;
if(r2 <= chance)
call++;
}
cout << "Chance is " << chance << ": " << call << " invocations or "
<< ((100.0 * call) / 100000.0) << "% of the time!" << endl;
return call;
}
可以预见,我得到了这些结果:
Chance is 0.1: 10216 invocations or 10.216% of the time!
Chance is 0.2: 20232 invocations or 20.232% of the time!
Chance is 0.3: 30357 invocations or 30.357% of the time!
Chance is 0.4: 40226 invocations or 40.226% of the time!
Chance is 0.6: 60539 invocations or 60.539% of the time!
Chance is 0.7: 70539 invocations or 70.539% of the time!
Chance is 0.8: 80522 invocations or 80.522% of the time!
Chance is 0.9: 90336 invocations or 90.336% of the time!
Chance is 1: 100000 invocations or 100% of the time!
您想添加多少个湖泊?
答案 1 :(得分:-1)
在致电randomize()
之前尝试rand()
。