有大神来看看吗?我是想用二分法同时得到两个解,但是到最后我都不知道自己编的啥了,但是能得到正确答案!
#include<iostream>
using namespace std;
double fx(double x)
{
return x*x - x - 2;
}
const double esp = 1.e-5;
double L, R, M, a;
double fL, fM;
double root(double);
int main()
{
cout << "单调区间左端点L="; cin >> L;
cout << "单调区间右端点R="; cin >> R;
cout << "请输入求解步长:";
cin >> a;
while (1)
{
if (fx(L)*fx(L + a) > 0)
L = L + a;
else
{
L = L - a;
cout << "①解为:" << root(L)<<endl; break;
}
if (L > R)
{
cout << "非有解区间!";
break;
}
}
L = L + 3*a;
while (1)
{
if (fx(L)*fx(L + a) > 0)
L = L + a;
else
{
L = L - a;
cout << "②解为:" << root(L)<<endl; break;
}
if (L > R)
{
cout << "非有解区间!";
break;
}
}
system("pause");
return 0;
}
double root(double L)
{
while (fabs(R - L) > esp)
{
M = (2 * L + a) / 2;
fL = fx(L);
fM = fx(M);
if (fL*fM < 0)R = M;
else if (fL*fM>0)L = M;
else break;
}
return M;
}