我在 C++ 中应用 Regula Falsi 方法,但问题在于 == 运算符当 F(x3) 变为 0 然后if (fabs( f(x3))==0应该停止并从循环中出来但它不会停止为什么为什么为什么.... 像第 12 次迭代后的输出 f(x3)=0 但是 if(fabs(f(x3)==0)) 没有运行。循环没有停止它不应该进入第 13 次迭代
float f(float x)
{
float f_x;
f_x= pow(x,3)+(3*x)-5;
return f_x;
}
int main(int argc, char** argv)
{
float a,b,tol,x3;
int itr,n;
cout << "enter the iterations";
cin >> itr;
cout << "enter the interval a";
cin >> a;
cout <<"enter the interval b";
cin >> b;
cout << "enter the toleration";
cin >> tol;
cout.setf(std::ios_base::fixed, std::ios_base::floatfield);
cout.precision(5);
//cout<<"fa="<<f(a)<<"fb"<<f(b);
cout<<"n\t\ta\t\tb\t\tx3\t\tf(a)\t\tf(b)\t\tf(x3)" <<endl;
if (f(a)*f(b)<0 && a<b)
{
for (n=0;n<itr;n++)
{
x3=a-((b-a)*f(a))/(f(b)-f(a));
cout << "xx"<<fabs(f(x3));
if (fabs( f(x3))==0)
{
cout << "Solution"<<fabs(f(x3));
break;
}
else
{
cout<<n+1 <<"\t\t"<<a <<"\t\t"<<b <<"\t\t"<<x3<<"\t\t"<<f(a)
<<"\t"<<f(b)<<"\t\t"<<f(x3) <<endl;
if(f(x3)*f(a)<0)
b=x3;
else
if(f(x3)*f(b)<0)
a=x3;
}
}
}
else
cout<< "No Solution Exist";
return 0;
}
输出
进入迭代13
输入区间 a1
输入区间 b2
输入容忍度1
**n a b x3 f(a) f(b) f(x3)**
1 1.00000 2.00000 1.10000 -1.00000 9.00000 -0.36900
2 1.10000 2.00000 1.13545 -0.36900 9.00000 -0.12980
3 1.13545 2.00000 1.14774 -0.12980 9.00000 -0.04487
4 1.14774 2.00000 1.15197 -0.04487 9.00000 -0.01542
5 1.15197 2.00000 1.15342 -0.01542 9.00000 -0.00529
6 1.15342 2.00000 1.15391 -0.00529 9.00000 -0.00181
7 1.15391 2.00000 1.15408 -0.00181 9.00000 -0.00062
8 1.15408 2.00000 1.15414 -0.00062 9.00000 -0.00021
9 1.15414 2.00000 1.15416 -0.00021 9.00000 -0.00007
10 1.15416 2.00000 1.15417 -0.00007 9.00000 -0.00003
11 1.15417 2.00000 1.15417 -0.00003 9.00000 -0.00001
12 1.15417 2.00000 1.15417 -0.00001 9.00000 0.00000
13 1.15417 2.00000 1.15417 -0.00000 9.00000 0.00000