如何在1和用户输入的数字之间生成随机数?

How can I generate random numbers between 1 and a number input by the user?

本文关键字:之间 数字 随机数 输入 用户      更新时间:2023-10-16

如何创建一个程序,从1 ->RAND_MAX ?

RAND_MAX必须是用户输入的数字。

#include <iostream>
#include <stdlib.h>
int main()
{
    using namespace std;
    int x;
    int y;

    Random:
    {
        x = rand();
        cout << x << endl;
    }
    y = y + 1;
    if (y == 10) {
        return 0;
    }
    goto Random;
}

免责声明: rand是一种快速而肮脏的方式来生成随机数,因为它可能不会完全均匀地生成数字,如果RAND_MAX (rand的上限)被定义为小于目标范围,您将遇到一些问题。在现代c++中,最好使用<random>头,如问题在整个范围内均匀地生成随机数


类似:

int main()
{
  int randMax;
  cin >> randMax;
  for (int y = 0; y < 10; y++)
  {
    int x = rand() % randMax; // Range = [0, randMax)
    cout << x+1 << endl; // Range = [1, randMax]
  }
}

哦,尽量避免goto(至少在我看来)。这里有两个关于它的问题