📄 work.cpp
字号:
#include<iostream>
#include<cmath>
using namespace std;
double f(double x)
{
return x*x+exp(-1.0*x);
}
int fibonacci(int n) // 求解Fibonacci数列
{
if(n==0||n==1) return 1;
else return fibonacci(n-1)+fibonacci(n-2);
}
void f_fibonacci(double a,double b,double x,double y,double l) //fibonacci法
{
int n=1; //计算迭代次数
while(fibonacci(n)<=(b-a)/l)
{
n++;
}
for(int k=1;k<=n-2;k++)
{
x=a+(b-a)*fibonacci(n-k-1)/fibonacci(n-k+1);
y=a+(b-a)*fibonacci(n-k)/fibonacci(n-k+1);
cout<<"迭代次数:"<<k<<" "<<"试探点为:"<<x<<" "<<y<<" "<<"函数值分别为:"<<f(x)<<" "<<f(y)<<endl;
if(f(x) >f(y)) a=x;
else b=y;
}
double m; //判别常数
cout<<"输入辨别常数:";
cin>>m;
y=x+m;
if(f(x)>f(y)) a=x;
else b=x;
cout<<"极小点:"<<(a+b)/2<<" "<<"函数值:"<<f((a+b)/2)<<endl;
}
void f_f2(double a,double b,double x,double y,double l) //0.168法
{
for(int k=1;;k++)
{
x=a+0.382*(b-a);
y=a+0.618*(b-a);
cout<<"迭代次数:"<<k<<" "<<"试探点为:"<<x<<" "<<y<<" "<<"函数值分别为:"<<f(x)<<" "<<f(y)<<endl;
if(f(x) >f(y)) a=x;
else b=y;
if((b-a) <l) break;
}
cout<<"极小点:"<<(a+b)/2<<" "<<"函数值:"<<f((a+b)/2)<<endl;
}
void main()
{
double a,b,l; //初始区间[a,b],精度l
cout<<"输入初始区间:";
cin>>a>>b;
cout<<"输入精度:";
cin>>l;
double x,y; //试探点x,y
/*int c;
cout<<"若选择用fibonacci法输入1,选用0.618法输入2:";
cin>>c;
switch(c)
{
case 1: f_fibonacci(a,b,x,y,l);
break;
case 2: f_f2(a,b,x,y,l);
break;
default: cout<<"error input";
}*/
cout<<"0.618法的结果如下:\n";
f_f2(a,b,x,y,l);
cout<<"fibonacci法的结果如下:\n";
f_fibonacci(a,b,x,y,l);
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -