c++ - 每次运行此 C++ 程序时如何获得不同的数字?

标签 c++

<分区>

我正在使用 rand() 生成随机数并将其显示在算术问题的上下文中。我每次都得到相同的两个数字。我如何让这些每次都不同?

#include <iostream>
#include<cstdlib>

using namespace std;

int main()
{

    int numberOne = rand()%1000;
    int numberTwo = rand()%1000;
    int numberThree = numberOne + numberTwo;
    char input;

    cout  << " " << numberOne << endl;
    cout <<  "+" << numberTwo << endl;
    cout << "----";
    cin.get();
    cout << numberThree << endl;
}

最佳答案

#include <iostream>
#include<cstdlib>

using namespace std;

int main()
{

    /* initialize random seed: */
    srand (time(NULL));

    int numberOne = rand()%1000;
    int numberTwo = rand()%1000;
    int numberThree = numberOne + numberTwo;
    char input;

    cout  << " " << numberOne << endl;
    cout <<  "+" << numberTwo << endl;
    cout << "----";
    cin.get();
    cout << numberThree << endl;
}

为了获得随机数,您需要提供种子。

关于c++ - 每次运行此 C++ 程序时如何获得不同的数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52231000/

相关文章:

c++ - 从 lua 脚本中创建一个新的 C++ 对象?

C++编译时类的子类列表

c++ - 将默认标志添加到 clang++ 或 g++

c++ - Win32 滚动条剪辑文本

c++ - 使用 Armadillo 矩阵库时用于 C++ 代码的 Makefile

C++通过引用其他类传递二维数组

c++ - C++中的静态构造函数?我需要初始化私有(private)静态对象

c++ - 使用表达式参数专门化模板

c++ - iOS 4 VOIP 应用程序在后台响应

C++ 我应该完全限定我的变量类型吗?