如何在C ++循环中生成不同的随机数字？

``for (int t=0;t<10;t++) { int random_x; srand ( time(NULL) ); random_x = rand() % 100; cout<<"\nRandom X = "<<random_x; }` `

`srand()`调用`srand()`循环外（在应用程序启动时只调用一次），您应该随机获得“随机”数字。

` `#include <iostream> #include <random> using namespace std; int main() { // Random seed random_device rd; // Initialize Mersenne Twister pseudo-random number generator mt19937 gen(rd()); // Generate pseudo-random numbers // uniformly distributed in range (1, 100) uniform_int_distribution<> dis(1, 100); // Generate ten pseudo-random numbers for (int i = 0; i < 10; i++) { int randomX = dis(gen); cout << "\nRandom X = " << randomX; } }` `

PS

` `srand ( time(NULL) ); for (int t=0;t<10;t++) { int random_x; random_x = rand() % 100; cout<< "\nRandom X = "<<random_x; }` `

` ` srand (time(NULL)); (int t=0;t<10;t++) { cout << rand() % 100 << endl; }` `

`srand`调用移到程序的开头。 就像现在这样，连续两次调用的时间可能是一样的，所以随机数发生器将在同一个地方重新开始。

` `#include <iostream> #include <windows.h> #include "time.h" int main(int argc, char*argv[]) { srand ( time(NULL) ); for (int t = 0; t < 10; t++) { int random_x; random_x = rand() % 100; std::cout << "\nRandom X = " << random_x << std::endl; } Sleep(50000); return 0; }` `

` `for (int t = 0; t < 10; t++){ srand(time(NULL)*t); random = rand() % GetScreenWidth(); }` `
` `/*this code is written in Turbo C++ For Visual Studio, code is in comment*/ int a[10],ct=0,x=10,y=10; //x,y can be any value, but within the range of //array declared randomize(); //there is no need to use this Visual Studio for(int i=0;i<10;i++) { a[i]=random(10); //use a[i]=rand()%10 for Visual Studio } cout<<"\n\n"; do { ct=0; for(i=0;i<x;i++) { for(int j=0;j<y;j++) { if(a[i]==a[j]&&i!=j) { a[j]=random(10); //use a[i]=rand()%10 for Visual Studio } else { ct++; } } } }while(!(ct==(x*y)));` `

` ` int x; srand ( time(NULL) ); x = rand() % 1000 * rand() % 10000 ; cout<<x;` `