c语言生成1 - 100的不重复随机数

rt
要1到100的一百个数全部出现

#include<stdio.h>
#include<time.h>
#include<stdlib.h>
int Rand(int X,int Y)//生成随机数
{
int temp;
if(X>Y)
{
temp=X;
X=Y;
Y=temp;
}
return rand()%(Y-X+1)+X; 

}

void main()
{
int arr[100];
int i;
int r;
int temp;
srand((unsigned)time(NULL));
for(i=0;i<100;i++) arr[i]=i+1;//将数组赋值1~100
for(i=0;i<100;i++)
{
r=Rand(0,99);
temp=arr[i];
arr[i]=arr[r];
arr[r]=temp;
}//数组乱序
for(i=1;i<=100;i++)
{
printf("%3d ",arr[i-1]);
if(i%10==0)
printf("\n");


}


}

 

温馨提示:答案为网友推荐,仅供参考
第1个回答  2015-10-22
/*
7 29 89 2 63 35 34 82 96 87 69 6 44 12 5 93 4 67 46 83
Press any key to continue
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define N 20
int main() {
int i,j,flag,num,a[N];
srand((unsigned)time(NULL));
for(i = 0; i < N; ++i) {
num = rand()%98 + 1;
flag = 1;
for(j = 0; j < i; ++j) {
if(num == a[j]) {
flag = 0;;
break;
}
}
if(flag) a[i] = num;
else --i;
}
for(i = 0; i < N; ++i)
printf("%d ",a[i]);
printf("\n");
return 0;
}
第2个回答  2019-08-25
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>
#include<time.h>
int main()
{
/*1到100随机不重复数*/
int randnum[100];
srand((unsigned int)time(NULL));
randnum[0] = rand() % 100 + 1;
for (int i = 0;i < 100;i++)
{
flag:
randnum[i] = rand() % 100 + 1;
for (int j = 0;j < i;j++)
{
if (randnum[i] == randnum[j])
{
goto flag;
}
}
}
for (int i = 1;i < 101;i++)
{
printf("%d\t", randnum[i-1]);
if(i%10==0)
printf("\n");
}
printf("\n");
/*将100个数再排序*/
int max=0;
for (int i = 0;i < 100;i++)
{
for (int j = 0;j < 99;j++)
{
if (randnum[j] > randnum[j + 1])
{
max = randnum[j];
randnum[j] = randnum[j + 1];
randnum[j + 1] = max;
}
}
}

for (int i = 1;i < 101;i++)
{
printf("%d\t", randnum[i - 1]);
if (i % 10 == 0)
printf("\n");
}
system("pause");
return EXIT_SUCCESS;
}
第3个回答  2020-12-30
c语言生成1 - 100的不重复随机数?根据你的要求我已经将代码实现如下
#include<stdio.h>
#include<time.h>
#include<stdlib.h>
int main(){
int a[10];
srand((unsigned)time(NULL));
for(int i=0;i<10;i++){
A: a[i]=rand()%99+1;
for(int j=0;j<i;j++){
a[i]=rand()%99+1;
if(a[i]==a[j])goto A;
else break;
}
}
for(int i=0;i<10;i++)
printf("%d ",a[i]);
}
第4个回答  2015-10-24
这是生成1 - 100的不重复随机数函数
int Rand(int X,int Y)//生成随机数
{
int temp;
if(X>Y)
{
temp=X;
X=Y;
Y=temp;
}
return rand()%(Y-X+1)+X;

}