C 中的随机数和不同数 [英] Random and Different Numbers in C
本文介绍了C 中的随机数和不同数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试用 C 生成 7 个数字.代码应包含:
I am trying to generate 7 numbers in C. The code should contain:
- 不能以 0 开头.
- 数字必须在 0-9 之间
- 数字必须彼此不同.(例如:不能有两个 5,比如这个:7 5 8 3 2 5 4).
我的代码正在运行.不是从 0 开始的.数字是在 0-9 之间随机生成的.
My code is working. It doesn't start with 0. Numbers are randomly generated between 0-9.
但我无法包含第三件事.当我启动代码时,相同的数字即将到来.你知道我怎样才能产生不同的结果吗?
But I can't manage to include third thing. Same numbers are coming when I start the code. Do you know how can I generate all differently?
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <locale.h>
#include <time.h>
int main() {
srand(time(NULL));
int numbers[10];
int i;
for (i = 0; i < 7; i++) {
numbers[i] = rand() % 10;
if (numbers[0] == 0) {
numbers[0] = 1 + rand() % 9;
}
printf(" %d ", numbers[i]);
}
getch();
return 0;
}
推荐答案
Using permutation (Knuth 洗牌算法)
Using permutation (Knuth shuffle algorithm)
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <time.h>
static int rrand(int range)
{
return (int)((double)range * (rand() / (RAND_MAX + 1.0)));
}
static void randomize(int arr[], int size)
{
while (size > 1)
{
int item = rrand(size--);
int temp = arr[size];
arr[size] = arr[item];
arr[item] = temp;
}
}
int main(void)
{
int arr[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
int size = sizeof arr / sizeof *arr;
srand((unsigned)time(NULL));
while (arr[0] == 0)
{
randomize(arr, size);
}
for (int i = 0; i < 7; i++)
{
printf("%d\n", arr[i]);
}
}
这篇关于C 中的随机数和不同数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文