第4章 程序段的反复执行4.2while语句P128练习题(题及答案)

发布于:2025-08-10 ⋅ 阅读:(18) ⋅ 点赞:(0)

((1)阅读程序

#include <bits/stdc++.h>
using namespace std;
//汤永红
int main(){
	int n,s=0;
	cin >> n;
	while(n){
		s = s * 10 + n % 10;
		n /= 10;
	}
	cout << s << endl;
	return 0;
}

分别输入:0 1024 1234567890

输出结果:0 4201 987654321

((2)阅读程序

#include <bits/stdc++.h>
using namespace std;
//汤永红
int main(){
	int n;
	cin >> n;
	while(n != 0){
		cout << n % 2;
		n /= 2;
	}
	return 0;
}

输输入: 4 0

输输出:001 无输出

#include <bits/stdc++.h>
using namespace std;
//汤永红
int main(){
	int n,sum = 0;
	cin >> n;
	while(n){
		sum += n % 10;
		n /= 10;
	} 
	cout << sum << endl;
	return 0;
}

#include <bits/stdc++.h>
using namespace std;
//汤永红
int main() {
	int n, m, i, j;
	cin >> n >> m;
	i = n;
	j = m;
	while(i != j) {
		if(i > j)
			i -= j;
		else
			j -= i;
	}
	if(i == 1)
		cout << "Yes";
	else
		cout << "No";

	return 0;
}

#include <bits/stdc++.h>
using namespace std;
//汤永红
int main(){
	int l,r,ans = 0;
	cin >> l >> r;
	for(int i = l;i <= r; i++){
		//拆位
		int x = i;
		while(x){
			int c = x % 10;
			if(c == 2) ans++;
			x /= 10;
		} 
	}
	cout << ans << endl;
	return 0;
}

#include <bits/stdc++.h>
using namespace std;
//汤永红
int main() {
	int n, K;
	double Sn, An;
	printf("Please input K(1<=K<=15):");
	scanf("%d", &K);
	if ((K >= 1) && (K <= 15)) {
		n = 1;
		while(1) {
			An = 1.0 / n;
			Sn += An;
			if (Sn > K) {
				break;
			}
			n++;
		}
		printf("n=%d,Sn=%f\n", n, Sn);
	} else {
		printf("Input error!Please input again!\n");
	}

	return 0;
}

I(2016)love(08)China(15)!
L(2016)oryh(08)Fklqd(15)!
#include <bits/stdc++.h>
using namespace std;
//汤永红
char c;
int main() {
	while((c = getchar() ) != '\n') {
		if(islower(c)) {
			putchar('a' + (c - 'a' + 3) % 26);
		} else if(isupper(c)) {
			putchar('A' + (c - 'A' + 3) % 26);
		} else {
			putchar(c);
		}
	}
	return 0;
}


网站公告

今日签到

点亮在社区的每一天
去签到