繁体   English   中英

需要生成4个随机数,而无需在C编程中重复。 1到4

[英]Need to generate 4 random numbers without repetition in C programming. 1 to 4

我想使用C编程以随机方式生成数字1到4。 我已经准备好直接在while循环中打印a[0] ,对于其他元素,程序将检查从a[1]a[3]的新数字是否与前面的任何元素相同。 已经为此创建了一个功能。 int checkarray(int *x, int y)

该函数通过减少传递的地址来逐一检查当前元素和先前的元素。 如果它与值匹配,则通过为条件变量赋值零来退出循环( int apply )。

return apply;

main节目它与匹配int check如果check==1 ,该号被打印,否则循环被重复。

面临的问题:生成的随机数在2到4之间变化。例如

2 4
2 4 3 
1 3 3 4

等等

有时也有重复。

#include <stdio.h>
#include <conio.h>

int checkarray(int *x, int y);

void main() {
    int a[4], i = 0, check;

    srand(time(0));

    while (i < 4) {
        a[i] = rand() % 4 + 1;
        if (i == 0) {
            printf("%d ", a[i]);
            i++;
            continue;
        } else {
            check = checkarray(&a[i], i);
        }
        if (check == 1) {
            printf("\n%d ", a[i]);
        } else {
            continue;
        }
        i++;                    
    }

    getch();
}

int checkarray(int *x, int y) {
    int arrcnt = y, apply = 1, r = 1;
    while (arrcnt > 0) {
        if (*x == *(x - 2 * r)) {
            apply = 0;
            exit(0);
        } else {
            arrcnt--;
            r++;
            continue;
        }
    }   
    return apply;
}

让我们看一下checkarray函数,该函数应该检查数组中是否已经存在数字。

这样称呼:

check = checkarray(&a[i], i);

其中a是4个整数的数组,而i是实际的索引,因此它将尝试向后扫描该数组以查找a[i]任何出现

int checkarray(int *x,int y)
{
    int arrcnt=y,apply=1,r=1;
    while(arrcnt>0)
    {
        if(*x==*(x-2*r))
        //         ^^^    Why? This will cause an out of bounds access.
        {
            apply = 0;
            exit(0);    // <-- This ends the program. It should be a 'break;'
        }
        else
        {
            arrcnt--;
            r++;
            continue;
        }
    }   
    return apply;
}

无需更改接口(我认为这很容易出错),可以将其重写为

int check_array(int *x, int y)
{
    while ( y )
    {
        if ( *x == *(x - y) )   
            return 0;
        --y;
    }
    return 1;
}

在这里可测试。

尽管还有许多其他问题需要解决,所以请也来看看这些问答。

“ n *(rand()/ RAND_MAX)”会产生倾斜的随机数分布吗?
人们为什么说使用随机数生成器时存在模偏差?
C语言中的Fisher Yates改组算法
C中的int main()与void main()
为什么在Linux上找不到<conio.h>?

您的方法很乏味,但可以使它起作用:

  • 不需要特殊情况下的第一个数字,只需使checkarray()返回未找到空数组即可。
  • 您应该将不同的参数传递给checkarray() :指向数组的指针,要检查的条目数和要搜索的值。
  • 您不应该使用exit(0)checkarray()返回0:它会使程序立即终止。

这是修改后的版本:

#include <stdio.h>
#include <conio.h>

int checkarray(int *array, int len, int value) {
    int i;
    for (i = 0; i < len; i++) {
        if (array[i] == value)
            return 0;
    }
    return 1;
}

int main() {
    int a[4], i = 0, value;

    srand(time(0));

    while (i < 4) {
        value = rand() % 4 + 1;
        if (checkarray(a, i, value)) {
            printf("%d ", value);
            a[i++] = value;
        }
    }
    printf("\n");
    getch();
    return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM