-4

重複の可能性:
範囲全体で一様に乱数を生成する
C++ random float

c++ で 5 から 25 までの乱数を生成するにはどうすればよいですか?

#include <iostream>
#include <cstdlib>
#include <time.h>

using namespace std;

void main() {

    int number;
    int randomNum;

    srand(time(NULL));

    randomNum = rand();

}
4

4 に答える 4

12

rand() % 20実行して、5 ずつ増やします。

于 2011-11-18T16:35:33.050 に答える
6

C++11 の場合:

#include <random>

std::default_random_engine re;
re.seed(time(NULL)); // or whatever seed
std::uniform_int_distribution<int> uni(5, 25); // 5-25 *inclusive*

int randomNum = uni(re);

または、次のようにすることもできます。

std::uniform_int_distribution<int> d5(1, 5); // 1-5 inclusive
int randomNum = d5(re) + d5(re) + d5(re) + d5(re) + d5(re);

これにより、同じ範囲で異なる分布が得られます。

于 2011-11-18T16:42:35.430 に答える
2

C++ の方法:

#include <random>

typedef std::mt19937 rng_type; // pick your favourite (i.e. this one)
std::uniform_int_distribution<rng_type::result_type> udist(5, 25);

rng_type rng;

int main()
{
  // seed rng first!

  rng_type::result_type random_number = udist(rng);
}
于 2011-11-18T16:44:14.090 に答える
0
#include <cstdlib>
#include <time.h>

using namespace std;

void main() {

    int number;
    int randomNum;

    srand(time(NULL));

    number = rand() % 20;
cout << (number) << endl;

}
于 2011-11-18T16:38:31.320 に答える