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

练习:闰年、位数、简易计算器

引入

章前总览 三道练习:嵌套 / else if 判闰年;多分支判几位数;switch 做四则与取余计算器。

三道练习:

  • 闰年:层层二分或 else if
  • 位数:从大到小或从小到大
  • 计算器:按运算符字符 switch

1 练习1:闰年(多分支实现)

要求用多分支结构判断闰年,输出 yes / no。

</> 嵌套写法

#include <iostream>
using namespace std;

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

2 练习2:判断是几位数

输入小于 10000 的正整数 n,输出位数(1~4)。

</> 从大到小(推荐)

#include <iostream>
using namespace std;

int main() {
    int n;
    cin >> n;
    if (n >= 1000) cout << 4 << endl;
    else if (n >= 100) cout << 3 << endl;  // 不必再写 n<=999
    else if (n >= 10) cout << 2 << endl;
    else cout << 1 << endl;
    return 0;
}
  • 前面分支已排除更大范围,后面条件不要画蛇添足。
  • 从小到大:n<10 → 1;n<100 → 2;……
  • 样例:1234 → 4。

3 练习3:简单的计算器

输入 x y c,c 为 + − * / %,用 switch 输出整数运算结果。

</> 参考代码

#include <iostream>
using namespace std;

int main() {
    int x, y;
    char c;
    cin >> x >> y >> c;
    switch (c) {
        case '+': cout << x + y << endl; break;
        case '-': cout << x - y << endl; break;
        case '*': cout << x * y << endl; break;
        case '/': cout << x / y << endl; break;  // 整数除法
        case '%': cout << x % y << endl; break;
    }
    return 0;
}
  • 样例:13 5 / → 2;13 5 % → 3。
  • case 后可以是字符常量。
小结

选型口诀:

区间/复合条件 → if / else if
离散几个常量值 → switch 更清爽
里程碑达成:

下一节做第9章基础知识自测。