시간 ()을 사용하는 C / C ++, 랜드 ()은 하나의 난수, 난수 생성 시퀀스 번호를 생성하는 난수 생성

문제 해결은 종종, 임의의 번호를 사용하여 임의의 숫자를 많이 생성 할 필요 특히, 임의의 숫자, 임의의 숫자를 생성에 대해 공유 할 수있는 간단한 방법을 명령했다.

컴파일러 사용 VC6.0

① 난수를 생성
#include<ctime> 
#include<iostream>
using namespace std;
#define random() (rand()%x)   //定义随机值的范围 0~x 
int main(int argc, char* argv[])
{	
	cout<<rand()%100<<endl;  //输出一个100以内的随机值
	return 0;
}

연속하는 3 동작 예의 결과
여기에 그림 삽입 설명
여기에 그림 삽입 설명
여기에 그림 삽입 설명
ctime이 헤더가 난수를 생성하는, 상기 코드는 전혀 존재하기 때문에 각각의 실행에 대해 임의의 숫자가 동일하지만, 난수 생성 없다설정 임의 화;
코드를 추가합니다 :

srand((unsigned)time(NULL)); 
#include<ctime> 
#include<iostream>
using namespace std;
#define random() (rand()%x)   //定义随机值的范围 0~x 
int main(int argc, char* argv[])
{	
	srand((unsigned)time(NULL));//设置随机数种子
	cout<<rand()%100<<" "<<endl;  //输出一个100以内的随机值
	return 0;
}

세 개의 연속적인 실행 예 결과 :
여기에 그림 삽입 설명
여기에 그림 삽입 설명
여기에 그림 삽입 설명

큰 임의의 데이터와 순서를 생성 ②

의 다음 사용 C ++ STL 컨테이너와 반복자는 , 목록은 이중 예를 들어, 목록 컨테이너를 연결 500 개 단위는 임의의 숫자를 주문 만들

#include<ctime> 

#include<iostream>

#include<iomanip>

#include<list>         //list双链表容器头文件

using namespace std;

#define random() (rand()%x)   //定义随机值的范围 0~x 

int main(int argc, char* argv[])
{	
	srand((unsigned)time(NULL));//设置随机数种子
	
	list<int> a; //定义一个int型的动态数组a
	
	for(int i=0;i<500;i++)
		{
		a.push_back(rand()%10000);     //尾端插入链表
		a.sort();       //升序排序
		a.unique();//去除重复元素
		}
	
	list<int>::iterator it;  //构建一个list容器的迭代器it
	
	
	
	cout<<"-------------------------------五百个递增有序随机数---------------"<<endl;
	
	for( it = a.begin();it!=a.end();it++)
	{

		cout<<setw(4)<<*it<<" ";   //取list容器中的值输出
	
	}
	
	cout<<endl;
	
	return 0;
}

실행 샷 :
여기에 그림 삽입 설명

추천

출처blog.csdn.net/qq_41767945/article/details/90682070