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()。请注意,srandrand是C语言中的旧历史工件,使用最新的C ++编译器随附的更现代的生成器会更好,

有关更多信息,请参见c++ random number generators上的文档

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...