我必须在1-50之间生成一对随机整数。然后我需要让我的程序生成五个与两个随机整数具有相同范围的其他数字。我知道如何生成第一对但是Iam无法为其他5创建生成。顺便说一下,这就是C ++。
答案 0 :(得分:1)
假设我理解您的问题,以下方法适合我。
请注意,5个数字将具有相同的delta:
给出的绝对差值int delta = abs(pairOne.x - pairOne.y);
但是你没有提到是否x> y或y> x是一个约束(一个简单的修改可以启用它)。代码只是找到具有保证差异(delta)的随机数,如下所示。
#include <iostream>
#include <random>
struct RandPair {
int x;
int y;
};
int main()
{
// A Mersenne Twister pseudo-random generator:
typedef std::mt19937 CppRNG;
// Seed the generator:
uint32_t seed_val = 0;
CppRNG RandomGenerator;
RandomGenerator.seed(seed_val);
int min = 1;
int max = 50;
std::uniform_int_distribution<uint32_t> uniformMinMax(min, max);
RandPair pairOne;
RandPair otherPairs[5];
pairOne.x = uniformMinMax(RandomGenerator);
pairOne.y = uniformMinMax(RandomGenerator);
std::cout << pairOne.x << "; " << pairOne.y << std::endl;
int delta = abs(pairOne.x - pairOne.y);
int count = 0;
while (count < 5) {
int r1 = uniformMinMax(RandomGenerator);
int r2 = uniformMinMax(RandomGenerator);
if ( abs(r1 - r2) == delta && count < 5 ) {
otherPairs[count].x = r1;
otherPairs[count].y = r2;
count++;
}
}
for (int i = 0; i<5; i++) {
std::cout << "delta: " << delta << "; " << otherPairs[i].x << "; " << otherPairs[i].y << std::endl;
}
return 0;
}
答案 1 :(得分:1)
此解决方案需要#include <random>
和支持C ++ 11的编译器。
std::random_device rd;
std::mt19937 mt(rd());
std::uniform_int_distribution<int> r1(1, 50);
int first = r1(mt), second = r1(mt);
if (first > second) std::swap(first, second);
std::uniform_int_distribution<int> r2(first, second);
for (int i = 0; i < 5; ++i) {
std::cout << r2(mt) << '\n';
}
答案 2 :(得分:-1)
int a, b, low, high;
a = rand()%50 + 1;
b = rand()%50 + 1;
low = min(a,b);
high = max(a,b);
int ar[5];
int range = high-low+1;
for(int i=0; i<5; ++i) {
ar[i] = rand()%(range) + low;
}
答案 3 :(得分:-1)
这样的事情应该有效:
void printRandomNumbers( int low, int high )
{
// Seed the random number generator.
srand( time(0) )
// Generate 2 random numbers between low and high (inlcusive).
int a = ( rand() % ( high-low ) ) + ( low + 1 );
int b = ( rand() % ( high-low ) ) + ( low + 1 );
// Find a new low and new high.
if ( a <= b )
{
low = a;
high = b;
} else {
high = a;
low = b;
}
printf("The new low is: %d\nThe new high is: %d\n", low, high);
// Print 5 numbers inside the new range.
for ( int i = 0; i < 5; i++ )
{
printf( "%d\n", rand() % ( high-low ) + ( low + 1 ) );
}
}
int main()
{
printRandomNumbers(0, 100);
}
如果您不想重复数字,则需要跟踪输出。最简单的方法是使用基本的c数组[]。