B63
练习:闰年求和、奇数和、各位最大值
引入
章前总览 继续练 for/while + if:开区间闰年求和;负数奇数用 t%2 判断;取位过程中更新最大值。
三道练习:
- 闰年求和:不含两端
- 奇数和:if(t%2) 兼容负数
- 各位最大值:while 取位 + 擂台
1 练习1:闰年求和
两个年份之间(不含起始与终止)的闰年年份数字之和。
参考代码
#include <iostream>
using namespace std;
int main() {
int s, t, sm = 0;
cin >> s >> t;
for (int y = s + 1; y < t; y++) {
if (y % 400 == 0 || (y % 4 == 0 && y % 100 != 0))
sm += y;
}
cout << sm << endl;
return 0;
}
- 循环写成
y=s+1; y<t,不要包含两端。 - 样例:2018 2022 → 2020;2000 2004 → 4004。
2 练习2:求奇数的和
输入 n 及 n 个整数(可含负),求其中奇数之和。
负数奇数
- 负奇数对 2 取余可能是 −1,不能写死
t%2==1。 - 推荐:
if (t%2) s+=t;或t%2!=0。
参考代码
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
int t, s = 0;
for (int i = 1; i <= n; i++) {
cin >> t;
if (t % 2) s += t; // 不要只写 t%2==1
}
cout << s << endl;
return 0;
}
- 样例:8 个数含 −8 → 347。
3 练习3:求各位数字的最大值
输入正整数,输出各位数字中的最大值。样例:43015 → 5。
参考代码
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
int mx = 0;
int t = n;
while (t) {
if (t % 10 > mx) mx = t % 10;
t = t / 10;
}
cout << mx << endl;
return 0;
}
- while 取位 + if 更新最大值 = 循环嵌套分支。
小结
三种常见组合:
for + if → 扫区间计数/累加
for + if → 读 n 个数再筛选
while + if → 取每一位再比较
✓
里程碑达成:
下一节做第12章基础知识自测。