1. 程式人生 > >時間戳和隨機數的總結以及顯示年月日與時間的函式

時間戳和隨機數的總結以及顯示年月日與時間的函式

    時間戳是指從1970年1月1日到此刻一共的時間秒數。Windows上C庫函式time(NULL),產生隨機數函式一般是利用時間戳。
    但是首先應該有個概念:計算機不會產生絕對的隨機數,計算機只能產生“偽隨機數”,“偽”是有規律的意思,就是計算機產生的偽隨機數既是隨機的又是有規律的。
    有關時間戳和隨機數的函式:
    time(NULL);   時間戳
    srand(time(NULL));設定隨機數種子
    rand();
    注意:srand(a) ,它只是定義了一種規則,當a的值確定時,產生的隨機數不會發生變化,因為time(NULL)是每一秒在變化的(概念),這也是利用他做產生隨機數的原因之一。
    改進:因為time(NULL)的變化週期是1s,所以當產生隨機數的週期<1s時,產生的隨機數不會發生變化,可以加變數k---->srand(time(NULL)+k++);
    rand()%n+1:產生的隨機數範圍是1--n;


附自己寫的小程式,初學階段,有很多可以改進和錯誤的地方望大家指正!!!
實時顯示當前年月日及時間,用到 /  %;
注:平年閏年:能被4整除不能被100整除 || 能被400整除 是閏年,2月29天


#include <stdio.h>

#include <time.h>

{
void my_time();
void my_ymd();
void mt_select();
void mt_pmonth();

void mt_rmonth();

int key;

int month1[12]={31,28,31,30,31,30,31,31,30,31,30,31};  //平年
int month2[12]={31,29,31,30,31,30,31,31,30,31,30,31};  //閏年


int main()
{
my_ymd();
my_time();


return 0;
} void my_ymd()
{
/*time1是當前時間戳,days是1970年一月一日到現在的天數
tyear是年的週期數(平、平、平、閏,1461天一個週期)
dyear是不足一個週期的天數,t_year是1970+週期*4*/


int time1,days,tyear,dyear;
int t_year;


time1=time(NULL);
days=time1/(24*60*60);   //當前時間戳對一天的總秒數去整,得到總天數
tyear=days/1461;         //總天數對1461取整得到週期數
dyear=days%1461;         //得到不足一個週期的天數
t_year=1970+tyear*4;     //當前年份


if(dyear<365)
{
printf("%d年是平年,當前時間是:%d 年 ",t_year,t_year);

key=1;


mt_select(dyear);
}


if(dyear<365+365)
{
t_year+=1;
dyear-=365;

printf("%d年是平年,當前時間是:%d 年 ",t_year,t_year);

key=1;


mt_select(dyear); //將不足一年的天數作為實參傳至mt_select函式中
}

if(dyear<365+365+365)
{
t_year+=2;
dyear-=(365+365);

printf("%d年是平年,當前時間是:%d 年 ",t_year,t_year);

key=1;

mt_select(dyear);
}

else
{
t_year+=3;
dyear-=(365+365+365);

printf("%d年是閏年,當前時間是:%d 年 ",t_year,t_year);

key=0;

mt_select(dyear);
}
}

void mt_select(int m)                  //根據平年和閏年選擇計算月份的函式
{
switch(key)
{
case 1:mt_pmonth(m);break;   //m接收的dyear,傳至sday1
case 0:mt_rmonth(m);break;
}

}


void mt_pmonth(int sday1)              //計算月份,sday1:平年一年內剩的天數
{
int i,temp,nmonth,nday;


for(i=0;i<12;i++)             //對月份的陣列相減,得到月份
{
temp=sday1-month1[i];


sday1=temp;

nmonth=i+1;


if(temp<=0)
{
printf("%d月 ",nmonth);

break;
}
}
nday=temp+month1[i];


printf("%d日\n",nday);
}


void mt_rmonth(int sday2)              //計算月份,sday2:閏年一年內剩的天數
{


int i,temp,nmonth,nday;

for(i=0;i<12;i++)
{
temp=sday2-month1[i];

sday2=temp;

nmonth=i+1;


if(temp<=0)
{
printf("%d月 ",nmonth);


break;
}
}
nday=temp+month2[i];


printf("%d日\n",nday);

}

void my_time()
{
int shi,time1,shi1,shi2;
int fen,fen1,fen2,miao,miao1,miao2;


while(1)    //死迴圈,使不斷的獲取當前時間戳
{
time1=time(NULL);

shi=time1%(24*60*60)/(60*60)+8;
shi1=shi/10;
shi2=shi%10;


fen=time1%(24*60*60)%(60*60)/60;
fen1=fen/10;
fen2=fen%10;

miao=time1%(24*60*60)%(60*60)%60;
miao1=miao/10;
miao2=miao%10;


printf("%d%d:%d%d:%d%d\r",shi1,shi2,fen1,fen2,miao1,miao2);
}

printf("\n");
}