B59
练习:折纸、折半、各位和
引入
章前总览 三道“做到某个条件为止”的题:厚度翻倍直到超过高度;不断 /2 直到变成 0;累加每一位数字。
三道练习:
- 折纸:while (ch < h) ch*=2
- 折半:while (n) n/=2
- 各位和:s += t%10; t/=10
1 练习1:折纸
纸厚 0.1 mm,每次对折厚度×2。输入高度 h(米),问对折多少次达到或超过 h。
参考代码
#include <iostream>
using namespace std;
int main() {
int n = 0;
double h, ch = 0.1; // 毫米
cin >> h;
h = h * 1000; // 米 → 毫米
while (ch < h) {
ch = ch * 2;
n++;
}
cout << n << endl;
return 0;
}
- 样例:1.80 → 15;8848.86 → 27(超过珠峰)。
2 练习2:折半
正整数 n 每次取一半(整数除法),多少次后变成 0。样例:10 → 4(10→5→2→1→0)。
参考代码
#include <iostream>
using namespace std;
int main() {
int n, cnt = 0;
cin >> n;
while (n) {
n /= 2;
cnt++;
}
cout << cnt << endl;
return 0;
}
- 条件也可写
n>0;直接while(n)更简洁。
3 练习3:求各位数字之和
输入正整数,输出各位数字之和。样例:43015 → 13。
参考代码
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
int s = 0;
int t = n;
while (t) {
s += t % 10;
t = t / 10;
}
cout << s << endl;
return 0;
}
- 与“统计位数”同一套取位技巧,只是把计数改成累加。
小结
条件循环模板:
while (还没达到目标) {
更新状态;
计数或累加;
}
✓
里程碑达成:
下一节做第11章基础知识自测。