Ok, this is my code. I half the segment if the root is in it until the segment length reaches an error tolerance.
Code:
#include <stdio.h>
#include <math.h>
float f(float x)
{
return (x-5);
}
void Halfing ()
{
float a,b,s,e;
int n = 0;
int test = 0;
do
{
printf("Enter the beginning of the segment -> ");
scanf("%f",&a);
printf("Enter the end of the segment -> ");
scanf("%f",&b);
if ((f(a) > 0 && f(b) > 0) || (f(a) < 0 && f(b) < 0))
{
printf("The root is not inside the segment [%4.2f,%4.2f]",a,b);
printf("\nChoose other endpoints\n");
}
else test = 1;
} while (test != 1);
printf("Enter error tolerance -> ");
scanf("%f",&e);
if (f(a) == 0) printf("The root is at an endpoint and it is %6.4f\n",a);
else if (f(b) == 0) printf("The root is at an endpoint and it is %6.4f\n",b);
else
{
do
{
n++;
s = (a+b)/2;
printf("%d. pass x = %6.4f\n",n,s);
if (f(a)*f(s)<0) b = s;
else a = s;
} while (fabsf(a-b)>e);
printf("\nRoot = %6.4f", (a+b)/2);
}
}
int main (int argc, const char * argv[])
{
Halfing ()
return 0;
}