0

I have 2 main if statements inside this for loop (lines 7 and 56). I'm trying to get so that if after all the iterations are complete, i.e. j = 51 the first and second if statements are not satisfied, then it will print out an error message. I have currently tried to do this with another if else statement, however at the moment this is getting printed out no matter what.

Can anyone please explain how to do this?

```
for (double j = -50; j <= 51; j=j+0.1)
{
f(B, j, p, degree);
if ( f(B, j, p, degree) <= 0 && f(B, j+0.1, p, degree) > 0 )
{
cout << "\nA root is between the interval (" << j <<","<< j+1 <<")"<<endl;
left_endpoint = j;
x1 = left_endpoint;
f1 = f(B, x1, p, degree);
right_endpoint = j+1;
xmid = right_endpoint;
fmid = f(B, xmid, p, degree);
width = (right_endpoint - left_endpoint);
for (int i = 1; i <= max; i++)
{
x2 = (x1 + xmid) / 2.0;
cout << "The next midpoint, approximation is " <<fixed<<setprecision(7)<< x2 << endl;
f2 = f(B, x2, p, degree);
if (f1 * f2 <= 0.0) // root is in left half interval
{
current_width = (x2 - x1) / 2.0;
fmid = f2;
xmid = x2;
}
else // root is in right half interval
{
current_width = (xmid - x2) / 2.0;
f1 = f2;
x1 = x2;
}
if (current_width < epsilon)
{
cout << "\nA root at x = " << x2 << " was found "
<< "in " << i << " iterations" << endl;
f2 = f(B, x2, p, degree);
cout << "The value of the function at the root is " << f2 << endl;
break;
}
}
}
else if ( f(B, j, p, degree) >= 0 && f(B, j+0.1, p, degree) < 0 )
{
cout << "\nA root is between the interval (" << j <<","<< j+1 <<")"<<endl;
left_endpoint = j;
x1 = left_endpoint;
f1 = f(B, x1, p, degree);
right_endpoint = j+1;
xmid = right_endpoint;
fmid = f(B, xmid, p, degree);
width = (right_endpoint - left_endpoint);
for (int i = 1; i <= max; i++)
{
x2 = (x1 + xmid) / 2.0;
cout << "The next midpoint, approximation is " <<fixed<<setprecision(7)<< x2 << endl;
f2 = f(B, x2, p, degree);
if (f1 * f2 <= 0.0) // root is in left half interval
{
current_width = (x2 - x1) / 2.0;
fmid = f2;
xmid = x2;
}
else // root is in right half interval
{
current_width = (xmid - x2) / 2.0;
f1 = f2;
x1 = x2;
}
if (current_width < epsilon)
{
cout << "\nA root at x = " << x2 << " was found "
<< "in " << i << " iterations" << endl;
f2 = f(B, x2, p, degree);
cout << "The value of the function at the root is " << f2 << endl;
break;
}
}
}
else if (j = 51)
{
cout << "\nThe search for a root has failed. The polynomial you have entered"
<< "\ncontains one or more complex roots." << endl;
//break;
}
}
```

*Edited
by sexyzebra19*: n/a