我试图在 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/