c - 随机化 4 个不同的数字

标签 c

我试图在 C 中随机化 4 个不同的数字并尝试下一个代码:

{
    int num1 = 0, num2 = 0, num3 = 0, num4 = 0;
    int i = 0;
    while (num1 == num2 && num1 == num3 && num1 == num4 && num2 == num3 && num2 == num4 && num3 == num4 && num3 == num2)
    {
        num1 = rand() % 7;
        num2 = rand() % 7;
        num3 = rand() % 7;
        num4 = rand() % 7;
    }
    printf("%d %d %d %d\n", num1, num2, num3, num4);
}

代码假设检查数字是否不相等,如果它们相等,它需要生成新数字直到它们完全不同。 但出于某种原因,它运行不佳,即使是正确的数字也会被误认为是错误的,并变成无限循环。

我错过了什么?

最佳答案

此代码将在 0 .. 6 范围内选择 4 个不同的数字,它通过创建一个可用数字数组来工作,因为每个被选择的数字都会从列表中删除。

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define RANGE   7                   // how many different numbers
#define PICK    4                   // how many to pick

int main(void) {
    int pool[RANGE];
    int size, n, i;
    for (size=0; size<RANGE; size++) {
        pool[size] = size;          // create number pool 0..6
    }
    srand((unsigned)time(NULL));

    // pick different numbers
    for(i=0; i<PICK; i++) {
        n = rand() % size;          // random array index
        printf("%d ", pool[n]);     // select number from pool
        pool[n] = pool[--size];     // remove from pool
    }
    printf("\n");
    return 0;
}

关于c - 随机化 4 个不同的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34569182/

相关文章:

c - 将查询传递给没有第一个字符的字符串

c - 如何在不影响其他位的情况下将 uint8_t 放在 uint16_t 中间

c - sem_init 分段故障错误

c - 在优化中迷失/困惑

c++ - 具有现有起始值的 C/C++ for 循环

c - 使用 FILE* 从 Arduino tty 中读取

ctrl+c 不发送 SIGKILL 进行处理

c - 解引用指向不完整类型的指针 - 使用指向函数的指针将值分配给结构

c - 为什么 OpenProcessToken 会因 ERROR_ACCESS_DENIED 而失败

C 运行时计算器