首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

C 語言 if-else 中 %10 餘數運算與 st/nd/rd 序數詞尾綴說明

     編輯:程式設計綜合問答

代碼片段

if (n % 10 == 1 && n % 100 != 11) suffix = "st";
else if (n % 10 == 2 && n % 100 != 12) suffix = "nd";
else if (n % 10 == 3 && n % 100 != 13) suffix = "rd";
else suffix = "th";

%10 含義

取模(餘數)運算**:`n % 10` 回傳 `n` 除以 10 的餘數,即 **個位數字**。

  • `21 % 10 = 1` → 個位是 1
  • `22 % 10 = 2` → 個位是 2
  • `23 % 10 = 3` → 個位是 3

st / nd / rd / th 含義

英文**序數詞**尾綴:

基數序數縮寫規則
onefirst1st個位 1,但 11 例外
twosecond2nd個位 2,但 12 例外
threethird3rd個位 3,但 13 例外
four~fourth~4th~其餘皆 th

為什麼要 `n % 100 != 11/12/13`?

英語中 **11, 12, 13(及 111, 112, 113...)是特例**,統一用 `th`:

  • 11th (eleventh)、12th (twelfth)、13th (thirteenth)
  • 故判斷邏輯:先看最後兩位是否為 11~13,是 → `th`;否 → 再看個位決定 `st/nd/rd/th`。

完整範例輸出

1  → 1st
2  → 2nd
3  → 3rd
4  → 4th
11 → 11th (例外)
12 → 12th (例外)
13 → 13th (例外)
21 → 21st
22 → 22nd
23 → 23rd
111 → 111th (例外)

總結

`%10` 取個位數字;`st/nd/rd` 對應 first/second/third 縮寫;`11/12/13` 為語言學例外需額外排除。此邏輯常用於日期顯示(1st Jan)、排名列表、頁碼等國際化場景。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved