rand() 函数通过升序到前一个数字来生成下一个数字

rand() function generates the next number by ascending to the previous number

本文关键字:数字 一个 下一个 函数 升序 rand      更新时间:2023-10-16

请检查下面给出的代码。它为每次执行生成的随机数是上一次执行中先前生成的数字的增量。

#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int main()
{
    srand(time(NULL));
    cout<<"n Random Number : "<<rand()<<endl;
    cin.get();
    return 1;
}

请执行它 5-6 次,您将看到每次执行的随机数都在增加,并且它们彼此非常接近。

注意:请使用CodeBlocks或Visual studio来检查它,而不是在线编译器。

实际上我找到了解决问题的方法,但它仍然可能不是我问题的答案。无论如何,问题不在于srand()rand()函数,而在于函数time(NULL)。由于我尝试在 Windows 上运行此代码,而不是使用 time(NULL) 作为srand()的参数,我使用了GetTickCount(),现在它为每次执行正确生成随机数。

#include <iostream>
#include <cstdlib>
#include <windows.h>
using namespace std;
int main()
{
    srand(GetTickCount());
    cout<<"n Random Number : "<<rand();
    cout<<"n";
    cin.get();
    return 1;
}
相关文章: