如何在C ++中存储随机数

时间:2015-09-20 20:30:37

标签: c++ random srand

到目前为止,我已经创建了一个使用srandrand创建随机数的程序。

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int main()
{

    srand(time(0));

    for(int x = 1; x<25;x++) {
        cout << 1+ (rand()%6);
    }

}

如何使用int存储随机数?

1 个答案:

答案 0 :(得分:4)

  

如何使用int存储随机数?

正如我的评论中提到的那样,只需完成分配int变量而不是输出它:

int myRandValue = 1+ (rand()%6);

但听起来您希望在生成后可以使用整套生成的值。

您可以将随机数存储在std::vector<int>中,如下所示:

std::vector<int> myRandValues;
for(int x = 1; x<25;x++) {
    myRandValues.push_back(1+ (rand()%6));
}

然后从另一个循环中访问它们,如

for(auto randval : myRandValues) {
    cout << randval << endl;
}