C++ 小知識點(diǎn)

預(yù)處理器

  • "#include、#define、#if、#else、#line 等
  • "#define 預(yù)處理
  • 函數(shù)宏
  • 條件編譯

常量

  • define
  • const

有符號整數(shù)和無符號整數(shù)之間的差別

#include <iostream>

using namespace std;

int main() {
    // short int 2個字節(jié) 16位
    short int i;           // 有符號短整數(shù)
    unsigned short int j;  // 無符號短整數(shù)
    j = 50000;
    i = j;
    cout << i << endl << j;
    return 0;
}
-15536
50000

無限循環(huán)

#include <iostream>

using namespace std;

int main() {
    for (;;) {
        printf("This loop will run forever.\n");
    }
    return 0;
}

cmath 庫

隨機(jī)數(shù)

#include <iostream>

using namespace std;

int main() {
    // 設(shè)置種子
    srand((unsigned) time(NULL));
    for (int i = 0; i < 10; ++i) {
        cout << rand() % 10 << '\t';// [0...9]隨機(jī)數(shù) 
    }
    return 0;
}

C++ 日期 & 時間

#include <iostream>
#include <ctime>

using namespace std;

int main() {
    time_t now = time(0); // 基于當(dāng)前系統(tǒng)的當(dāng)前日期/時間

    // 把 now 轉(zhuǎn)換為字符串形式
    char *strDate = ctime(&now); // 參數(shù)為 time_t * 類型
    cout << "本地日期和時間:" << strDate << endl;

    // 把 now 轉(zhuǎn)換為 tm 結(jié)構(gòu)
    tm *gmtm = gmtime(&now); // 返回一個指向 time 的指針,time 為 tm 結(jié)構(gòu),用協(xié)調(diào)世界時 (UTC)(GMT)
    strDate = asctime(gmtm); // 參數(shù)為 tm * 類型
    cout << "UTC 日期和時間:" << strDate << endl;

}
本地日期和時間:Sat May 13 14:13:36 2017

UTC 日期和時間:Sat May 13 06:13:36 2017
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。