隨機函數rand()的小程序:
#include<iostream>
#include <time.h>
#include <fstream>
#include <windows.h>
using namespace std;
unsigned t[300],temp;
void creat_rand() //產生隨機數的函數
{
long i=1;
cout<<"為您產生的隨機數如下:"<<endl;
srand(time(0)); //用此函數設定種子值,使每次產生的隨機數不一樣
for(i=1;i<21;)
{
temp=(rand()%10000+1000);
if(temp>999 && temp<=9999)
{
t[i]=temp;
cout<<"第"<<i<<"個"<<t[i]<<" ";
if(i%5==0)
cout<<endl;
i++;
}
}
}
void search_number(unsigned t[],int n)//查找函數
{
cout<<endl;
DeleteFile("randnumber.txt");
system("pause");
cout<<"後兩位數字相等的隨機數:"<<endl;
ofstream output("randnumber.txt",ios::out);
int cand1,cand2;
for(int i=1;i<n;i++)
{
cand1=t[i]%10;
cand2=t[i]%100/10;
if(cand1==cand2)
{
cout<<t[i]<<" ";
output<<t[i]<<" ";
}
}
output.close();
}
void main()//主函數
{
creat_rand();
search_number(t,20);
}