到目前为止,我已经创建了一个使用srand
和rand
创建随机数的程序。
#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
存储随机数?
答案 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;
}