我在C++中應用Regula Falsi方法,但問題是當F(x3)變爲0時使用==運算符,然後if(fabs(f(x3))== 0應該停止並且從環路出來,但它不會停止爲什麼爲什麼爲什麼.... 像12日迭代F(X3)= 0,但如果(晶圓廠(F(X3)== 0))後,下方輸出不運行。循環不停止它不應該去第13次迭代C++ ==操作符不工作
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;
}
輸出
在大多數情況下,進入iterations13
進入區間A1
進入區間B2
進入toleration1
**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
它可能是一個非常小的值,但不爲零(並且您在打印時不會看到它) - 您可以嘗試將條件從「== 0」更改爲「
Leeor
這是可怕的代碼。浮點數等於另一個的條件幾乎無法通過計算來滿足。 **不要那樣做**。 – Walter