C++第三章课后练习题

编写可以求两个数最大公约数和最小公倍数的函数。

复制代码
 1 #include <iostream>
 2 #include <cmath>
 3 using namespace std;
 4 int fun1(int x,int y)
 5 {
 6     int temp;
 7     if(x<y)
 8     {
 9          temp=x;
10         x=y;
11         y=temp;
12      }
13      while(y!=0)          //辗转相除法,也叫欧几里得算法,直到余数等于零,所除的除数就是最大公约数 
14      {
15          temp=x%y;
16          x=y;
17          y=temp;
18       } 
19       return x;
20 }
21 int fun2(int x,int y)
22 {
23     return x*y/fun1(x,y);
24 }
25 int main()
26 {
27     int a,b;
28     cin>>a>>b;
29     cout<<fun1(a,b)<<endl;
30     cout<<fun2(a,b)<<endl;
31 }
复制代码

编写函数用递归的方法求1+2+...+n的值

复制代码
 1 #include <iostream>
 2 using namespace std;
 3 int fun(int x)
 4 {
 5     if(x==1)
 6     {
 7         return 1;
 8     }
 9     else
10     {
11         return fun(x-1)+x;
12     }
13     
14 } 
15 int main()
16 {
17     int n;
18     cin>>n;
19     cout<<fun(n)<<endl;
20 }
复制代码

编写函数用递归函数求斐波那契数列的第n项。

复制代码
#include <iostream>
using namespace std;
int fun(int x)
{
    if(x==1||x==2)
    {
        return 1;
    }
    else
    {
        return fun(x-1)+fun(x-2);
    }
    
} 
int main()
{
    int n;
    cin>>n;
    cout<<fun(n)<<endl;
}
复制代码

用递归的方法编写函数求n阶勒让多德多项式的值,在主程序中实现输入输出。

复制代码
 1 #include <iostream>
 2 using namespace std;
 3 float fun(float n,float x)
 4 {
 5     if(n==0)
 6     {
 7         return 1;
 8     }
 9     if(n==1)
10     {
11         return x;
12     }
13     if(n>1)
14     {
15         return ((2*n-1)*x*fun(n-1,x)-(n-1)*fun(n-2,x))/n;
16     }
17     
18  } 
19 int main()
20 {
21     double a,b;
22     cin>>a>>b;
23     cout<<fun(a,b)<<endl;
24 }
复制代码

 

posted @   新晋软工小白  阅读(131)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示