用C中的4个唯一随机数填充数组 [英] Fill an array with 4 unique random numbers in C
本文介绍了用C中的4个唯一随机数填充数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
对于一个学校项目,我需要做MasterMind,而且密码的所有4个数字都必须不同。
For a school project I need to do MasterMind, and all the 4 numbers of the secret code have to be different.
如何创建具有4个唯一随机数的数组?
How can I create an array with 4 unique random numbers?
到目前为止,这是我的代码:
Here is my code so far:
srand(time(NULL));
for (j = 0; j <= 4; j++) { rand(); }
for (i = 0; i < 4; i++) { vetor[i] = (1 + rand() % 8); }
推荐答案
代码中的问题:
-
j循环徒劳地运行
The j-loop is running in vain
您不检查重复项
解决方案:
这是一个工作代码,在代码注释中有解释:
Here is a working code with explanation in the code comments:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
// Going to be filled with 4 unique random numbers
int arr[4];
// Set the seed
srand(time(NULL));
// Get 4 random numbers
for (int i = 0; i < 4; i++)
{
// Fill arr[i] with a random number from your specified range
arr[i] = 1 + rand() % 8;
// Try again if it is a duplicate
for (int j = 0; j < i; ++j)
{
if (arr[i] == arr[j])
{
--i;
break;
}
}
}
// Print the array and see the results
for (int i = 0; i < 4; ++i) printf(" %d", arr[i]);
return 0;
}
这篇关于用C中的4个唯一随机数填充数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文