Having troubles exiting the while loop once the correct root has been found (value of r3 == 0). Should I be using a break somewhere, if so - where?
I have already tried playing around with the conditional for the if, else if and else statements. Tried placing the break; in different places but couldn't have it in such a way that I still received correct output (mostly it was breaking after the first iteration)
float fun(float t);
float fun(float t)
{
double result;
result = (cos(t) - t); //my function
return result;
}
void main()
{
float a; float b; float error; float root;
scanf("%f %f %f", &a, &b, &error); //scanning for range of bisection and maximum allowed error
int i = 0;
if (fun(a) == 0)
{
root = a;
printf("The root is : %f", a);
}
else if (fun(b) == 0)
{
root = b;
printf("The root is : %f", b);
}
else
{
while (i < 100)
{
float r1 = fun(a);
float r2 = fun(b);
root = (a+b)/2.0;
float r3 = fun(root);
printf("The root after %d iteration is %f\n",i,root);
if(r1*r3 < 0 && r3 != 0) //intermediate value theorem
{
b = root;
}
else if(r3*r2 < 0 && r3 != 0) //intermediate value theorem
{
a = root;
}
i++;
int *p = &i; //not necessary at this moment
}
}
printf("The approximation to the root is %f",root);
The expected result is that the program should end at the first time that r3 == 0 since that would been that the found root using the bisection method is correct. Therefore, the last iteration should be the one with the correct final value for the root...