C / C ++ - 002- generating random data

C / C + ± 002- generating random data -2020-3-7

C language

First, true random number

//真随机数
#include<stdio.h>
#include <stdlib.h> 
#include<time.h>
#include <stdio.h>
# define n 100
int a[101],i;
int main()
{
	srand((unsigned)time(NULL));//获取随机数种子,rand()产生0~32767之间的数 
	for(i=1;i<=n;i++)
	a[i]=rand()%100;
	for(i=1;i<=n;i++)
    printf("%d ",a[i]);
	getchar();
	return 0; 
} 
48 70 58 94 32 40 66 61 27 33 77 34 11 61 66 28 84 38 59 38 52 10 13 4 88 47 89 82 27 60 28 50 66 99 48 40 80 41 67 11 99 74 7 51 59 86 31 0 37 7 45 48 55 84 28 33 78 49 68 90 83 11 8 64 74 10 55 11 56 22 55 77 44 83 94 45 21 24 41 49 29 98 89 2 21 4 79 0 35 42 28 16 60 95 6 76 80 47 6 51

--------------------------------
Process exited with return value 0
Press any key to continue . . .

Second, to generate a random integer between 0 and 1

//产生0~1之间的随机数
#include<time.h>
#include<stdio.h>
#include <stdlib.h> 
int main()
{
	srand((unsigned)time(NULL));
	for(int i=1;i<=50;i++)
    printf("%d ",rand()%(2));
    system("pause") ;
	return 0;
} 
1 1 0 0 0 0 0 0 1 1 0 0 0 1 1 0 1 0 0 0 1 0 0 0 0 0 1 1 0 1 0 1 0 1 0 0 0 1 1 0 1 1 0 1 1 1 1 1 1 0 请按任意键继续. . .

--------------------------------
Process exited with return value 0
Press any key to continue . . .

Third, generating random integers in the range of low and hight

//产生指定范围内的随机数 
#include<time.h>
#include<stdio.h>
#include <stdlib.h> 

int main()
{
	
	int low,hight; 
	srand((unsigned)time(NULL));
	scanf("%d %d",&low,&hight);
	for(int i=1;i<=50;i++)
    printf("%d ",rand()%(hight-low+1)+low);
    system("pause") ;
	return 0;
} 
1 5
4 4 1 1 5 5 4 1 3 1 3 5 1 3 2 2 4 3 3 5 4 4 3 3 4 2 4 5 4 5 1 3 1 4 3 4 5 5 2 3 4 1 5 1 4 2 4 5 3 1 请按任意键继续. . .

--------------------------------
Process exited with return value 0
Press any key to continue . . .

C++

Generating a random string

//产生指定长度的随机字符串 
#include<time.h>
#include <stdlib.h> 
#include<string>
#include<iostream>
using namespace std;
int main()
{
	
	int i,n,m;//输出n行m个字符的随机字符串
	string str;
	cin>>n>>m;
	srand((unsigned)time(NULL));

	for(i=1;i<=n;i++)
	{
		str="";                 //清空字符串 
		for(int j=1;j<=m;j++)
		{
			int temp=rand()%2;              //随机决定输出大写或小写字母 
			if(temp==0)
			str+=(char)(rand()%(26)+1+64);//'A'=65,'Z'=90
			else
			str+=(char)(rand()%(26)+1+96);//'a'=97,'z'=122 
		}
		  cout<<str<<endl;
	}

 
    system("pause") ;
	return 0;
} 
3 5
IaHpG
eaMwW
MtMym
请按任意键继续. . .
Published 91 original articles · won praise 101 · Views 3306

Guess you like

Origin blog.csdn.net/weixin_41096569/article/details/104723150