一、十二进制逆序
#include<iostream>
using namespace std;
void tran12_reverse(int n)
{
cout<<hex<<n%12;
if(n>11)
tran12_reverse(n/12);
}
void tran12_order(int n)
{
if(n>11)
tran12_order(n/12);
cout<<hex<<n%12;
}
//除前余后
void main()
{
int n=220;
cout<<"逆序:";
tran12_reverse(n);
cout<<"\n正序:";
tran12_order(n);
cout<<endl;
}
正整数求各位和
#include<iostream>
using namespace std;
void f(int n,int &s)
{
s=s+n%10;
if(n>9)
f(n/10,s);
cout<<n%10<<' ';
}
void main()
{
int s=0;
int n=226;
cout<<n<<"正序:";
f(n,s);
cout<<"和为:"<<s<<endl;
}
二、递归求公约数
#include<iostream>
using namespace std;
//辗转相除法
int f(int a,int b)
{
if(a<b)
{int temp=a,a=b,b=temp;}
if(a%b==0)
return b;
else
f(b,a%b);
}
void main()
{
int a,b;
cout<<"输入两个整数,求它们的最大公约数:\n";
cin>>a>>b;
if(f(a,b)==1)
//只有,仅仅只有if()括号内为0时,才执行else,否则如-2,-1,2都执行语句1
cout<<"这两个数互质"<<endl;
else
cout<<f(a,b)<<endl;
}
三、求级数递归
#include<iostream>
using namespace std;
#include<math.h>
double f(float x,int n)
{
if(n==1)
return 1;
return -x*x/(2*(n-1)*(2*(n-1)-1))*f(x,n-1);
//除号后一定记得加括号,第一次写成-x*x/2*(n-1)*(2*(n-1)-1)*f(x,n-1);报错
}
#define E 0.00001 //误差1e-5
void main()
{
int i;
float x=1;
for(i=1;;i++)
{
if(abs(f(x,i))<E)
break;
}
cout<<"第"<<i<<"项为:"<<f(x,i);
cout<<"\n第"<<i-1<<"项为:"<<f(x,i-1)<<endl;
}
四、n阶Legendre多项式
#include<iostream>
using namespace std;
double legendre(float x,int n)
{
if(n==0)
return 1;
if(n==1)
return x;
return ((2*n-1)*x*legendre(x,n-1)-(n-1)*legendre(x,n-2))/n;
}
void main()
{
int n;
float x=1;
cout<<"请输入要求第几项legendre(从0开始):\n";
cin>>n;
cout<<legendre(x,n)<<endl;
}