【问题标题】:How do I store a random number in C++如何在 C++ 中存储随机数
【发布时间】:2015-09-20 20:30:37
【问题描述】:

到目前为止,我已经制作了一个使用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存储随机数?

【问题讨论】:

  • 使用int 变量?您实际上想存储它在哪里?
  • 存储任何int 的方式相同。如果您不知道该怎么做,您真的需要阅读C++ book。通过反复试验学习 C++ 根本行不通。
  • 您存储随机数的方式与执行确定性随机数完全相同 - 您将其分配给适当类型的变量。
  • 不确定您所说的“商店”是什么意思。在数据库中?在变量中?在文件中?
  • 只需int k=1+rand()%6

标签: c++ random srand


【解决方案1】:

如何使用int存储随机数?

正如我在评论中提到的,这只是分配一个 int 变量而不是输出它:

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

但听起来您希望在生成它们之后让整个生成值集可供使用。

您可以像这样简单地将随机数存储在 std::vector&lt;int&gt; 中:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多