在Win 7系統中,short 表示的范圍為 - 32767到 32767,而無符號的short表示的范圍為0 到 65535,其他類型的同理可推導出來,當然,僅當數字不為負的時候才使用無符號類型。
有些事情,當時接觸的時候模模糊糊,可是,當你在過些時間慢慢的回頭看他時,覺得頓然開悟。
下面的程序顯示了如何使用無符號類型,並說明了程序試圖超越整型的限制時所產生的后果。在編寫程序時切記不要超越這些類型所限制的范圍,否則很難找出問題。
#include<iostream> #define ZERO 0 using namespace std; #include<climits> int main() { short nu1 = SHRT_MAX; unsigned short nu2 = nu1; cout << "nu1 has " << nu1 << " and nu2 has " << nu2 << endl; cout << "如果每個數都加一呢?" << endl; nu1 = nu1 + 1; nu2 = nu2 + 1; cout << "Now nu1 has " << nu1 << " and nu2 has " << nu2 << endl<<endl; nu1 = ZERO; nu2 = ZERO; cout << "nu1 has " << nu1 << " and nu2 has " << nu2 << endl; cout << "如果每個數減一呢?" << endl; nu1 = nu1 - 1; nu2 = nu2 - 1; cout << "Now nu1 has " << nu1 << " and nu2 has " << nu2 << endl; cin.get(); return 0; }
程序運行結果:
nu1 has 32767 and nu2 has 32767
如果每個數都加一呢?
Now nu1 has -32768 and nu2 has 32768
nu1 has 0 and nu2 has 0
如果每個數減一呢?
Now nu1 has -1 and nu2 has 65535