介紹
ANSI組織定義了C標(biāo)準(zhǔn)和標(biāo)準(zhǔn)庫函數(shù)。
使用標(biāo)準(zhǔn)C函數(shù)優(yōu)點(diǎn):
使用標(biāo)準(zhǔn)C函數(shù)在任何平臺(tái)上都支持,使得同一個(gè)源碼,在Windows編譯運(yùn)行的結(jié)果和Linux上編譯運(yùn)行結(jié)果相同,無需更改代碼。
隨機(jī)數(shù)(rand)
產(chǎn)生指定范圍內(nèi)隨機(jī)數(shù)(1~100)
1
2
3
4
5
6
7
8
9
|
#include <stdio.h> #include <stdlib.h> int main() { for ( int i=0; i<10; i++) { printf ( "%d\n" , rand ()%100); } } |
每次運(yùn)行會(huì)發(fā)現(xiàn)得到的是個(gè)隨機(jī)數(shù)一樣,為了解決這個(gè)問題,使用srand設(shè)置一個(gè)種子(seed),每次啟動(dòng)保證種子不同。
1
2
3
4
5
6
7
8
9
10
11
|
#include <stdio.h> #include <stdlib.h> #include <time.h> int main() { srand ( time (NULL)); for ( int i=0; i<10; i++) { printf ( "%d\n" , rand ()%100); } } |
時(shí)間函數(shù)(time)
獲取當(dāng)前時(shí)間戳(單位:s),時(shí)間戳即為距離1970-01-01 00:00:00的秒數(shù)
1
2
3
4
5
6
7
|
#include <stdio.h> #include <time.h> int main() { time_t ts = time (NULL); printf ( "%d\n" , ( int )ts); } |
通過時(shí)間戳獲取年月日,時(shí)分秒,周幾
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
#include <stdio.h> #include <time.h> int main() { time_t ts = time (NULL); tm time = * localtime (&ts); int year = time .tm_year + 1900; int month = time .tm_mon + 1; int day = time .tm_mday; int hour = time .tm_hour; int min = time .tm_min; int sec = time .tm_sec; int week = time .tm_wday ; return 1; } |
通過年月日,時(shí)分秒,獲取time_t 時(shí)間戳
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
#include <stdio.h> #include <time.h> int main() { //時(shí)間為2017-07-15 21:38:30 tm time = {0}; time .tm_year = 2017 - 1900; time .tm_mon = 7 -1; time .tm_mday = 15; time .tm_hour = 21; time .tm_min = 38; time .tm_sec = 30; time_t ts = mktime (& time ); //獲得該天為周幾 tm time1 = * localtime (&ts); printf ( "周%d\n" , time1.tm_wday); return 1; } |
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,謝謝大家對服務(wù)器之家的支持。如果你想了解更多相關(guān)內(nèi)容請查看下面相關(guān)鏈接
原文鏈接:https://blog.csdn.net/woniu211111/article/details/75193960