gpt4 book ai didi

C++ Rnd() 故障

转载 作者:行者123 更新时间:2023-11-28 00:50:51 28 4
gpt4 key购买 nike

伙计们,我在运行程序时遇到了这个非常奇怪的错误。这是重要的代码:

变量(编辑):

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”值更改为什么,结果似乎都完全相同。尽管我将 lakeChance 的值更改得更高(即:0.5、0.7、0.9),但在每次启动时似乎都会调用 addLake 函数约 3 到 6 次。只有当我将“lakeChance”的值更改为 1 时,该函数才会一直被调用。顺便说一句,随机数生成器工作正常,所以结果每次都会有所不同。

最佳答案

我没有看到显然本身有什么问题。所以我尝试了以下代码:

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!

您要添加多少个湖泊?

关于C++ Rnd() 故障,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14167154/

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