第4章 程序段的反复执行3 do-whiile语句P139练习(题及答案)
(1)程序阅读
#include <bits/stdc++.h>
using namespace std;
//汤永红
int main() {int n;cin >> n;do {cout << n % 2;n /= 2;} while(n != 0);return 0;
}
输入4 输出:001
输入0 输出:0
#include <bits/stdc++.h>
using namespace std;
//汤永红
int main() {int i, n;cin >> n;i = n - 1;doi--;while(i > 1 && n % i != 0);cout << i;return 0;
}
输入100 输出:50
输入79 输出:1
输入2 输出:0
#include <bits/stdc++.h>
using namespace std;
//汤永红
int main() {int i = 1, s = 3;do {s += i++;if(s % 7 != 0) ++i;} while(s < 15);cout << i;return 0;
}
输出8
#include <bits/stdc++.h>
using namespace std;
//汤永红
int main() {int s = 1; // sign用来表示数值的符号double n = 1, pi = 0, t = 1; // pi开始代表多项式的值,最后代表π的值,n代表分母,// term代表当前项的值while (fabs(t) > 1e-6) { //检查当前项term的绝对值是否大于10的(-6)次方pi = pi + t; //当前项t累加到pi中n = n + 2; // n+2是下一项的分母s = -s; // s代表符号,与上一项相反的符号t = s / n; //求出下一项的值}pi = pi * 4; //π的值printf("pi=%10.6f\n", pi); //输出π的近似值return 0;
}
#include <bits/stdc++.h>
using namespace std;
//汤永红
int main() {int count = 1;float hight, dis;hight = 200;dis = 200;do {hight = hight / 2;dis += 2 * hight;count++;} while(hight >= 0.5);cout << "小球弹跳的总路程是:" << dis << endl;return 0;
}
//599.219
#include <bits/stdc++.h>
using namespace std;
int main() {char a[10];int b[10], lena;scanf("%s", a);lena = strlen(a);if (strchr(a, '-')) {printf("-");a[0] = '0';for (int i = 0; i < lena; i++) {a[i] = a[i + 1];}lena--;}for (int i = 0; i < lena; i++) {b[i] = a[i] - 48;}for (int i = lena - 1; i >= 0; i--) {if(b[i] != 0)printf("%d", b[i]);}return 0;
}
1/4
#include <iostream>
#include <algorithm>
using namespace std;
int main() {int n, j = 0, i = 0;cin >> n;while(n > j) {i++;j += i;}if(i % 2 != 0) {cout << j + 1 - n << '/' << i + n - j << endl;} elsecout << i + n - j << '/' << j + 1 - n << endl;return 0;
}
输出是8,不是9。
#include <bits/stdc++.h>
using namespace std;
//汤永红
int main() {long long x, maxy = 0;cin >> x;for(int i = x; i <= 2000000; i++) {maxy += 1;if(x % 2 == 0) {x = x / 2;if(x == 1) {cout << maxy;break;}} else {x = x * 3 + 1;}}return 0;
}