测评会员优惠活动进行中 · 开通 VIP,有效期内测评不限次 VIP 优惠中 · 测评不限次 立即查看
B44

案例:大月、闰年、大小写转换

引入

章前总览 三道题练逻辑表达式:多个月份用 or;闰年用“能被 4 整除且不能被 100 整除,或能被 400 整除”;字母区间用 and。

三道案例:

  • 大月:七个 or
  • 闰年:(y%4==0 and y%100!=0) or y%400==0
  • 大小写:区间判断 + 加减 32

1 案例1:大月还是小月

输入月份 1~12:有 31 天输出 big,否则 small。

</> 参考代码

#include <iostream>
using namespace std;

int main() {
    int m;
    cin >> m;
    if (m==1 or m==3 or m==5 or m==7 or m==8 or m==10 or m==12)
        cout << "big" << endl;
    else
        cout << "small" << endl;
    return 0;
}
  • 样例:12 → big;2 → small。

2 案例2:闰年的判断

闰年 366 天(2 月 29 天)。规则:① 能被 4 整除但不能被 100 整除;或 ② 能被 400 整除。

为什么这样定

  • 最初约 365.25 天 → 每 4 年加一天。
  • 更精确约 365.2425 天 → 每 400 年只要 97 个闰年,于是世纪年一般平年,但能被 400 整除的仍是闰年。
  • 例:2004、2000 闰年;2005、2100、1900 平年。

</> 参考代码

#include <iostream>
using namespace std;

int main() {
    int y;
    cin >> y;
    if ((y % 4 == 0 and y % 100 != 0) or y % 400 == 0)
        cout << "yes" << endl;
    else
        cout << "no" << endl;
    return 0;
}
  • 样例:2020 → yes;1900 → no。

3 案例3:大小写字母转换

输入一个字母:大写变小写,小写变大写(保证是字母)。

</> 参考代码

#include <iostream>
using namespace std;

int main() {
    char c;
    cin >> c;
    char c1;
    if (c >= 'A' and c <= 'Z')
        c1 = c + 32;  // 大写 → 小写
    else
        c1 = c - 32;  // 小写 → 大写
    cout << c1 << endl;
    return 0;
}
  • 样例:X → x;y → Y。
  • 也可用 c>='a' and c<='z' 判断小写,if/else 里的加减对调即可。
小结

闰年公式建议背下来:

(y%4==0 and y%100!=0) or y%400==0
里程碑达成:

下一节练习:工作日/周末、平年、图书馆老鼠。