在C++中,unsigned short
(通常簡寫為ushort
)是一種無符號整數類型,其大小通常為16位(2字節)
unsigned short
類型的數相加時,如果結果超出了unsigned short
的表示范圍(即大于USHRT_MAX
),則會發生模運算(即結果對USHRT_MAX + 1
取模)。這意味著結果將“環繞”到unsigned short
的有效范圍內。unsigned short a = USHRT_MAX; // 65535
unsigned short b = 1;
unsigned short c = a + b; // 0,因為 65535 + 1 = 65536 % (65536) = 0
unsigned short
類型的數相減時,如果結果小于0(即第一個數小于第二個數),則會發生模運算。unsigned short a = 0;
unsigned short b = 1;
unsigned short c = a - b; // 65535,因為 0 - 1 = -1 % (65536) = 65535
unsigned short
類型的數相乘時,如果結果超出了unsigned short
的表示范圍,則會發生模運算。unsigned short a = USHRT_MAX; // 65535
unsigned short b = 2;
unsigned short c = a * b; // 131070,因為 65535 * 2 = 131070 % (65536) = 131070
unsigned short
類型的數相除時,如果除數為0,則會發生未定義行為(UB)。否則,結果將被截斷為unsigned short
類型。unsigned short a = USHRT_MAX; // 65535
unsigned short b = 2;
unsigned short c = a / b; // 32767,因為 65535 / 2 = 32767
unsigned short
類型的數進行取模運算時,如果除數為0,則會發生未定義行為(UB)。否則,結果將被截斷為unsigned short
類型。unsigned short a = USHRT_MAX; // 65535
unsigned short b = 2;
unsigned short c = a % b; // 1,因為 65535 % 2 = 1
需要注意的是,當涉及到unsigned short
和其他整數類型(如int
、long
等)之間的運算時,可能會發生隱式類型轉換。在這種情況下,較小的整數類型將被提升為較大的整數類型,然后再進行運算。例如,當unsigned short
與int
相加時,unsigned short
將被提升為int
,然后再進行加法運算。