C++
第3章 函数
一、二进制转八进制
1:问题
2解答
#include <iostream>
using namespace std;
int power(int x,int n){
int y=1;//x=1,n=6,y=1
while(n--){
y=y*2;
}
return y;
}
int main(){
const int N=8;
int value=0;
for(int i=7;i>=0;i--){
char ch;
cin>>ch;
if(ch=='1'){
int z=static_cast<int>(ch);//返回的是字符串1的ACSII
value+=power(z,i);
}
}
cout<<value;
return 0;
}
8位二进制数当作char来处理,这里并不连续输入存储形成数组,而是输入立即判断与字符’1’,'0’是否相等,直接进行n次方的计算,最后累加
二、回文数
1问题描述
2解决代码
#include <iostream>
using namespace std;
bool hw(int m){
int n=m;//121
int sum=0;
while(n){
//while(!n)就是当n为0时继续运行 !!!!!!
sum=sum*10+n%10;//sum=1 //sum=1*10+2;//sum=12*10+1
n/=10;//n=12 //n=1 //n=0
}
if(sum==m){
return true;
}else {
return false;
}
}
int main(){
for(int i=11;i<1000;i++){
if(hw(i)==true && hw(i*i)==true && hw(i*i*i)==true){
cout<<i<<endl;
}
}
}
思考:本题该有两种思路1:逐个取字符,逐个对比,但数的位数不一定、每一个比较又略麻烦
2:个位变最高位…容易想到依次取每一位低位形成高位
三、sinx
1问题描述
2解决方案
#include <iostream>
#include <cmath>
using namespace std;
double tsin(double x){
double sum=0.0;
double y=x;//y=x=5
double i=1;
double f=i;//!!!不能除以整数
while(fabs(y/f)>=1e-10){
sum+=y/f;//sum=5/1 //5 -5*5*5/1*2*3 // 5/1 -5*5*5/1*2*3 +5^5/5!
y=-y*x*x;//y=-5*5*5 //y=5^5 //y=-5^7
f=f*(i+1)*(i+2);//1*2*3 //1*2*3* 4*5 //1*2*3 *4*5 *6*7
i+=2;//i=3,5,7
}
/*
while(fabs(y)>=1e-10){
sum+=y;//y自带多重 除
i++;
y=-y*x*x/(2*i-1)/(2*i-2);
}*/
return sum;
}
int main(){
double r,s;
cin>>r>>s;
if(r<=s){
double a=tsin(r)*tsin(r);
double b=tsin(s)*tsin(s);
double c=sqrt(a+b);
cout<<c<<endl;
}else{
cout<<tsin(r*s)/2<<endl;
}
return 0;
}
四、组合数
2解决方案
#include <iostream>
using namespace std;
//n选k个
int choose(int n,int k){
if(n<k){
cout<<"出错啦"<<endl;
}
else if(k==0){
return 1;
}
else if(n==k){
return 1;
}
else{
int f=choose(n-1,k)+choose(n-1,k-1);
return f;
}
}
int main(){
int n,k;//n中选k个人
cin>>n>>k;
cout<<n<<" 中选 "<<k<<" 个人 "<<endl;
cout<<choose(n,k);
return 0;
}
五、汉诺塔
1问题描述
2解决方案
#include <iostream>
using namespace std;
//将一堆盘子从一个移到另一个上hanoi
//移动一个move
void move(char plate1,char plate2){
cout<<plate1<<"-->"<<plate2<<endl;
}
void hanoi(int n,char start,char medium,char end){
if(n==1){
move(start,end);
}
else{
hanoi(n-1,start,end,medium);//其余的盘子先移走
move(start,end);//移动目标
hanoi(n-1,medium,start,end);//移走的也要移到end
}
}
int main(){
int n;//n层
cin>>n;
hanoi(n,'A','B','C');
return 0;
}
六、
#include <iostream>
using namespace std;
//最大公约数
int greatest(int a,int b){
int x=0;
for(int i=1;i<=a;i++){
if(a%i==0){
if(b%i==0){
x=i;
}
}
}
return x;
}
//最小公倍数:两者相乘除以最大公约数
int least(int a,int b){
if(greatest(a,b)==0){
return 0;
}
else{
return a*b/greatest(a,b);
}
}
int main(){
int a,b;
cin>>a>>b;
int c=greatest(a,b);
cout<<"最大公约数:"<<c<<endl;
int d=least(a,b);
cout<<"最小公倍数:"<<d;
return 0;
}
总结
cpp的库函数www.cppreferce.com
形参和实参结合:值传递、引用传递