【发布时间】:2013-09-22 03:09:35
【问题描述】:
我有这个代码:
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;
我能做什么?
【问题讨论】:
-
删除 goto: 错误的编程结构
-
一开始不要使用
goto -
不要在你的随机函数中使用 srand
-
详细阐述@Bathsheba 的评论:只需使用
break。 -
@thomas Ruiz 在这里是正确的;重复调用 srand 完全破坏了 randomn 序列。
标签: c++ random while-loop