Bisection Method Help

Hello new here.

I just want your help in my code.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include<iostream>
#include<cmath>
#define f(x) (6)*(x)*(x)*(x) + (5)*(x)*(x) + (7)*(x) - 2
using namespace 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;
	}
	else if (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;
			}
			else if (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.
Thank you sir. That solved the problem.
Topic archived. No new replies allowed.