用c语言生成一个四位数的随机数,但组成这个随机数的数字不重复,例如 1234 这四个数字里就没有重复的
求解答谢谢
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int my_rand()
{
int a[10] = {}, r = 0, x;
for (int i = 0; i < 4; i++)
{
do
{
x = rand() % 10;
} while (a[x] || (r == 0 && x == 0));
a[x] = 1;
r = r * 10 + x;
}
return r;
}
int main()
{
srand(time(NULL));
for (int i = 0; i < 10; i++)
printf("%d ", my_rand());
printf("\n");
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int num[4], cnt = 0, n;
srand(clock()); // 设置随机数种子
while (cnt < 4)
{
n = rand() % 4; // 生成4以内随机数,这样更利于测试
for (int i = 0; i < cnt; i++)
if (num[i] == n) // 遍历数组,有相同的重新生成随机数
continue;
num[cnt++] = n;
}
for (int i = 0; i < cnt; i++) // 打印随机数数组
printf("%d ", num[i]);
return 0;
}
#include<stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int t[4],j,k,count;
int n=4;
srand(clock());
for(j=0; j<4; j++)
{
count=0;
t[j]=rand()%10;
for(k=0; k<n; k++)
{
if(t[j]==t[k])
{
count++;
}
}
if(count>1)
{
j--;
}
}
for(j=0; j<4; j++)
printf("%d",t[j]);
printf("\n");
return 0;
}