编2歌简单的C++程序

来源:百度知道 编辑:UC知道 时间:2024/05/11 15:26:10
第一个 2/1,3/2,5/3,8/5,13/...求前20项的和

第二个
当n=0时y=0,当n=1时y=1,当n=2时y=2 当n>2时 y=y(下角标n-1)+y(下角标n-2)+y(下角标n-3)

/*1题的算法x=1,y=2 i=1
x=2,y=3 i=2
x(n)=x(n-1)+x(n-2) i>2
y(n)=y(n-1)+y(n-2)
在这用循环实现
*/

#include "stdio.h"
#include "iostream.h"

void main()
{
double x,y,tempx1,tempx2,tempy1,tempy2,sum=0.00;
//tempx1,tempx2,tempy1,tempy2记录临时变量
for(int i=1; i<=20; i++)
{
if(i==1)
{
x=1;
y=2;
tempx1=x;
tempy1=y;
}
if(i==2)
{
x=2;
y=3;
tempx2=x;
tempy2=y;
}
if(i>2)
{
x=tempx1+tempx2;
y=tempy1+tempy2;
tempx1=tempx2;
tempy1=tempy2;
tempx2=x;
tempy2=y;
}
sum+=y/x;
}
cout<<sum<<endl;
}

2题 同第一题的算法了,只是多加了一个,在这里用递归实现
#include "iostream.h"

double f(double n)
{
if (n<=2)
return n;