如何将斐波那契数列和后面的x结合,是否可以使用迭代法,比如n项待等于n-1项乘以一个式子
你这fun函数只有一个输入参数,没法用n-1项来计算第n项,但是仍然可以用递归。运行结果如下:
代码如下:
#include <iostream>
#include <math.h>
using namespace std;
double fun(double x)
{
static int a = 1, b = 2;
static int tm = 0;
static double sum = 0;
double fi = (double)a / b * pow(x, 2 * tm);
if (fi < 1.0e-6)
return sum;
else
{
if (tm % 2 == 0)
sum = sum + fi;
else
sum = sum - fi;
tm++;
int t = a + b;
a = b;
b = t;
}
fun(x);
return sum;
}
int main()
{
double x;
while (1)
{
cin >> x;
if (x > -1 && x < 1)
cout <<"f(x)=" << fun(x) << endl;
else
{
cout << "输入参数错误";
break;
}
}
return 0;
}
#include <iostream>
#include <cmath>
using namespace std;
int main() {
double fun(double x);
double x;
while(1){
cin >> x;
if(abs(x) > 1)
{
cout<<"参数有误"<<endl;
break;
}
cout << "f(x)=" << fun(x) << endl;
}
return 0;
}
double fun(double x)
{
double fper2(int x);
double f = 0;
int i;
for(;;++i){
double per1 = fper2(i + 1) * pow(x, 2 * i) * pow(-1, i);
double per = per1 / fper2(i + 2);
f += per;
if (abs(per) < 10e-16) break;
}
return f;
}
double fper2(int x)
{
if (x == 1) return 1;
else if (x == 2) return 2;
else return fper2(x - 2) + fper2(x - 1);
}
您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!