如何在C 程序中随机做一个

how to make a random in c++ program

本文关键字:一个 随机 程序      更新时间:2023-10-16

我想让我的程序选择一个随机数

 #include <iostream>
   using namespace std;
   int main(){
   int x=100 y=40;
   while (true)
     {if(x>y)
       {x--;}
     else
       {break;}}}

,除非您的编译器不支持C 11,否则请使用<random>库。您需要选择发动机,发动机的种子和分配;如果您不知道如何选择,并且想要一个随机整数,则应该这样做:

#include <random>
#include <iostream>
int main() {
    auto engine = std::mt19937(std::random_device()());
    auto distribution = std::uniform_int_distribution(0, 10); // between 0 and 10 inclusive
    auto random_integer = distribution(engine);
    std::cout << random_integer;
}