谭浩强C++ 第三章(2)

这篇博客涵盖了谭浩强C++教程第三章的课后习题,包括水仙花数、完数计算、分数列求和、猴子吃桃问题、迭代法求平方根及输出特定图案和乒乓球比赛名单等编程练习。

第三章课后习题(2)

19、水仙花数(三位数,各位数字的立方和等于该数字本身)
#include<iostream>
using namespace std;
int main(){
    int n,t;
    int n1,n2,n3;
    for(n=100;n<1000;n++){
    	t=n;
        n1=t/100;	
    	t=t%100;
    	n2=t/10;
    	t=t%10;
    	n3=t;
    	if(n1*n1*n1+n2*n2*n2+n3*n3*n3==n){
    		cout<<n<<" ";
		}
	}
	cout<<endl;
    return 0; 
}

水仙花数

20、1000以内的完数(数等于因数和)
#include<iostream>
#include<cmath>
using namespace std;
int main(){
	int i;
	int s;
    for(i=1;i<1000;i++){
    	s=1;
    	for(int j=2;j<=sqrt(i);j++){
    		if(i%j==0){
    			s=s+j+i/j;
			}
		}
		if(i==s){
			cout<<i<<",its factors are:";
			for(int j=1;j<=sqrt(i);j++){
    		    if(i%j==0){
    		    	if(j==1)   cout<<j<<" ";
    		    	else       cout<<j<<" "<<i/j<<" ";
				}
		    }
		    cout<<endl;
		}
	}
    return 0; 
}
21、分数列前20项和(2/1+3/2+5/3+8/5+…)
#include<iostream>
using namespace std;
int main(){
	double m=2.0,n=1.0;
	double s=0.0;
	double k;
	for(int i=0;i<20;i++){
		s+=m/n;
		k=n;
		n=m;
		m=m+k;
	}
	cout<<s<<endl; 
    return 0; 
}
22、猴子吃桃
#include<iostream>
using namespace std;
int f(int n){
	if(n==10)  return 1;
	if(n<10)  return (f(n+1)+1)*2; 
} 
int main(){
	//第十天1个桃子,说明第九天吃了第八天的一半加1,剩了1个 
	//递归
	cout<<f(1)<<endl; 
    return 0; 
}
23、迭代法求平方根
#include<iostream>
using namespace std;
int main(){
	double a;
	cin>>a;
	double x1=a,x2=(a+1)/2;
	while(1){
		if(x1-x2>-0.00001&&x1-x2<0.00001) break;
		double t=x2;
		x2=(x2+a/x2)/2;
		x1=t;
	}
	cout<<x1<<" "<<x2<<endl;
    return 0; 
}

24、输出图案
#include<iostream>
using namespace std;
void f(int n){
	for(int i=0;i<n;i++){
		cout<<"* ";
	}
	cout<<endl;
}
int main(){
	f(1); f(3); f(5); f(7); f(5); f(3); f(1);
    return 0; 
}
25、乒乓球比赛名单
#include<iostream>
using namespace std;
int main(){
	int m,n;
	//i j k代表甲队A B C 分别对应乙队人员的编号 
	for(int i=1;i<=3;i++){
		for(int j=1;j<=3;j++){
			if(i!=j){
				for(int k=1;k<=3;k++){
					if(k!=j&&k!=i){
						//cout<<i<<" "<<j<<" "<<k<<endl;
						if(i!=1&&k!=1&&k!=3){//甲队1号不对应乙队1号,甲队3号不对应乙队1,3号 
						//cout<<i<<" "<<j<<" "<<k<<endl;
							cout<<"A —— "<<char(65+22+i)<<endl;
							cout<<"B —— "<<char(65+22+j)<<endl;
							cout<<"C —— "<<char(65+22+k)<<endl;
						}
					}
				}
			}
		}
	}
    return 0;
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值