gpt4 book ai didi

c++ - 带有随机数的无限循环

转载 作者:搜寻专家 更新时间:2023-10-31 01:47:39 24 4
gpt4 key购买 nike

我有这个代码:

void generar() {

while (true) {
if (yPos == topOfTheWorld) {
scene[xPos][yPos] = 2;
} else if (yPos >= topOfTheWorld) {
scene[xPos][yPos] = 1;
} else if(yPos < topOfTheWorld) {
scene[xPos][yPos] = 0;
} else {
scene[xPos][yPos] = 0;
}

yPos++;

if(yPos>worldHeight) {
topOfTheWorld += 0;
yPos = 0;
xPos++;
}

if (xPos>worldWidth) {
break;
}
}

std::ofstream output("mapa.txt");
for(int y=0;y<worldHeight;y++) {
for(int x=0;x<worldWidth;x++) {
output<<scene[x][y];

if(x<(worldWidth-1)){output<<",";}
}
if(y<(worldHeight-1)){output<<std::endl;}
}

MessageBox(0, "World generation has finished!", "Finished!", MB_OK);

}

这会生成一个基于数组的世界。但是当我添加:

slope = random(5)-2;

收件人:

if(yPos == worldHeight) {
topOfTheWorld += 0; //There would be the slope var...

if(yPos == worldHeight) {
slope = random(5)-2;
topOfTheWorld += slope;

由于某些原因,while 变成了一个无限循环,我不知道为什么。

(随机函数)

#include <time.h>
#include <windows.h>

int random(int n = 0) {

srand(time(NULL));

if(n!=0){
return rand() % n;
} else {
return rand();
}

}

(变量)

const int worldWidth = 50;
const int worldHeight = 26;
int topOfTheWorld = worldHeight/2;
int xPos = 0;
int yPos = 0;
int scene[worldWidth][worldHeight];
int slope;

我能做什么?

最佳答案

你表明场景被定义为:

int scene[worldWidth][worldHeight];

但是,您的代码具有以下内容:

        if (xPos>worldWidth) {
break;
}

这意味着当 xPos == worldWidth 时,您实际上会在数组边界之外写入一个值,这会导致未定义的行为。添加 slope 变量可能会导致变量组织发生变化,从而导致未定义的行为最终影响循环控制变量的值和/或所有循环控制变量。

要修复,您应该更改错误检查:

        if (xPos>=worldWidth) {
break;
}

您已经使用代码编辑了您的问题,使您的 yPos 以类似的方式检查不正确。

关于c++ - 带有随机数的无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18935008/

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