我的代码处于无限循环中,我需要将其取出。它应该输出 5 行 3 列,每行没有重复

My code is in an infinite loop and I need it taken out. It should output 5 rows with 3 columns with no duplicates in each row

所以我的代码中有一个错误,使它陷入无限循环。我需要把它拿出来,但我一辈子都找不到它。

代码如下:

#include <iostream>
#include <cstdlib>

const int MAX             = 6;
const int SIZE_OF_SAMPLES = 3;
const int REP             = 5;

bool inArray     (int[], int, int  );
void UniqRandInt (int,   int, int[]);

int main() {
//   std::cerr<<"in main\n";

int arr[SIZE_OF_SAMPLES];

srand(9809);  //Seed random number generator.


for (int i = 0; i < REP; i++) {
    UniqRandInt(MAX, SIZE_OF_SAMPLES, arr);
    for(int j = 0; j < SIZE_OF_SAMPLES; j++) {
        std::cout << arr[i] << " ";
    }
    std::cout << std::endl;
}
return 0;
}
void UniqRandInt(int max, int n, int result[]) {

int cntr = 0, r;

while(cntr < n) {

    r = rand();  //Get random number
    r = r % (max + 1);
    if (inArray(result, cntr, r)) {
        result[cntr] =  r;
        cntr++;
    }
}
return;
}
bool inArray(int array[], int arrSize, int x) {
for (int i = 0; i < arrSize; ++i) {
    if (array[i] == x) {
        return true;
    }
}
return false;
}

它正在输出如下内容: 222 000 555 000 这是应该输出的内容: 就像是: 254 105 035 432 523 我需要 5 行所有不同的数字。

在 while 循环中

while(cntr < n) {

    r = rand();  //Get random number
    r = r % (max + 1);
    if (inArray(result, cntr, r)) {
        result[cntr] =  r;
        cntr++;
    }
}

如果 if 语句中的条件计算结果为假,则变量 cntr 不会递增。因此,如果生成数组 arr 的子数组中不存在的 r 值,则 while 循环将是无限的。

cntr 等于 0 时,循环第一次迭代的 r 的任何值都是不存在于由于这个函数定义的数组

bool inArray(int array[], int arrSize, int x) {
for (int i = 0; i < arrSize; ++i) {
    if (array[i] == x) {
        return true;
    }
}
return false;
}

因为在函数定义中,for 循环不会有迭代,控制权将传递给 return 语句

return false;

在这种情况下,for 循环看起来像

for (int i = 0; i < 0; ++i) {

如您所见,它的条件将计算为 false。

此外,如果您需要所有不同的数字,那么至少要满足 if 语句中的条件

if (inArray(result, cntr, r)) {

应该改写成

if ( not inArray(result, cntr, r)) {

似乎更改此 if 语句以获得预期结果就足够了(前提是代码没有任何其他逻辑或其他错误:))。

注意这个for循环有错别字

for(int j = 0; j < SIZE_OF_SAMPLES; j++) {
    std::cout << arr[i] << " ";
                 ^^^^^^
}

你需要写

for(int j = 0; j < SIZE_OF_SAMPLES; j++) {
    std::cout << arr[j] << " ";
                 ^^^^^^
}