如何解决C ++控制台应用程序中的“过程”游乐场生成
冒险学习基础知识和其他有关c ++的知识(总计noob)。现在,我为所有要访问的字段制作了一个Playground Array,但是当涉及到for循环中的rand()函数时,它会重复Nummber,因此不会随机生成。一些想法来解决这个问题?请注意,我不是很喜欢rand函数。 预先感谢!
这是我的代码
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
//**SETTINGS**
//Häufigkeit von field_type
#define VILLAGE 5
#define TOWN 2
int main()
{
//** THE PLAYGROUND **
struct field {
bool status;
string field_type;
};
int x = 5;
int y = 5;
field playground[5][5];
//Playground Typen definition
int village_counter = 0;
int town_counter = 0;
int x2 = 0;
int y2 = 0;
for (int counter = 0; counter < x * y; counter++) {
int Nummer;
srand(time(NULL));
Nummer = rand() % 4 + 1; // generates always the same number!
switch (Nummer) {
case 1:
village_counter++;
if (VILLAGE >= village_counter) {
playground[x2][y2].field_type = "VILLAGE";
}
else {
goto a_switch;
}
break;
case 2:
town_counter++;
if (TOWN >= town_counter) {
playground[x2][y2].field_type = "TOWN";
}
else {
goto b_switch;
}
break;
case 3:
a_switch:
playground[x2][y2].field_type = "GRASSLAND";
break;
case 4:
b_switch:
playground[x2][y2].field_type = "FOREST";
break;
}
x2++;
if (x2 == x) {
x2 = 0;
y2++;
}
}
//For test usage of all Field's
x2 = 0;
y2 = 0;
for (int counter = 0; counter < x * y; counter++) {
cout << counter << ": Field_TYPE = " << playground[x2][y2].field_type << endl;
x2++;
if (x2 == x) {
x2 = 0;
y2++;
}
}
}
解决方法
time
以秒为单位请求当前时间(整数)。如果您的程序执行时间少于一秒钟,那么您将每次以相同的值“播种”随机数生成器。伪随机数生成器(即您的rand()
调用)会根据您播种的状态返回确定性的一系列值。
正如@Scheff所说,最好只播一次(可能在程序的开头),然后在需要时调用rand()
。请注意,srand
和rand
是C语言中的旧历史工件,使用最新的C ++编译器随附的更现代的生成器会更好,
有关更多信息,请参见c++ random number generators上的文档
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。