#include<iostream>
#include<cmath>
#define f(x) (6)*(x)*(x)*(x) + (5)*(x)*(x) + (7)*(x) - 2
usingnamespace std;
int main()
{
int i = 1;
float a,b,c,e1,e2;
double a1,b1,c1,d;
cout<<"Welcome to the root solver."<<endl;
cout<<"We are going to find the root of 6x^3+5x^2+7x-2=0 using Bisection Method."<<endl;
cout<<"Enter the upper limit: ";cin>>a;
cout<<"Enter the lower limit: ";cin>>b;
cout<<"Enter the stopping error: ";cin>>e1;
a1 = f(a);
b1 = f(b);
if (a1==0)
{
c = a;
cout<<"The root is: "<<c<<"."<<endl;
}
elseif (b1==0)
{
c = b;
cout<<"The root is: "<<c<<"."<<endl;
}
else
{
while (a1*b1>0)
{
cout<<"The root is not found within the given limits. Please enter another limits."<<endl;
cout<<"Enter another upper limit: ";cin>>a;
cout<<"Enter another lower limit: ";cin>>b;
}
cout<<"Iterations\tXl\tXu\tXr\tf(Xl)\tf(Xu)\tf(Xr)\t"<<endl;
do
{
c = (a + b)/2;
c1 = f(c);
cout<<i<<"\t"<<b<<"\t"<<a<<"\t"<<c<<"\t"<<b1<<"\t"<<a1<<"\t"<<c1<<endl;
if (c1==0)
{
cout<<"The root is "<<c<<"."<<endl;
}
elseif (a1*c1<0)
{
b = c;
e2 = a - b;
}
else
{
a = c;
e2 = a - b;
}
i++;
}while(fabs(e2)>e1);
}
cout<<"The root is "<<c<<".";
system("pause");
return 0;
}
When I try to run it and input the limits where the root is found, it runs smoothly. But when I try to input limits that do no include the root to test my "while code" the program repeatedly ask for limits even if I try to write the possible limits.
You have computed a1 and b1 at lines 17 and 18. At the end of the while loop you need to re-compute a1 and b1 after inputting a and b. The while loop should go on forever as a1 and b1 are never changed.