Reputation: 7
I'm new and trying to learn bisection method in c. Here is my program so far:
#include<stdio.h>
#include<math.h>
double f(double x)
{
return pow(x,2)-2;
}
main()
{
double x1, x2, x3, i;
do
{
printf("Enter a number for x1 and x2");
scanf("%lf %lf", &x1, &x2);
}
if(f(x1)*f(x2)<0); /* **<--- if statement line 16** */
for(i=0;i<100;i++)
{
x3=(x1+x2)/2;
if (f(x1)*f(x3)<0)
x2=x3;
else
x1=x3;
if(f(x3)==0 || fabs(x1-x2)<0.000001) /* check if the roots*/
break;
}
print("x=%lf \n",x3);
return 0;
}
and I got this error message.
16:error: expected âwhileâ before âifâ
I know my code is janky, but I'm still learning. I don't know why its expected to have a while loop before an if loop there.
Upvotes: 0
Views: 48
Reputation: 223699
Right before the if
, you have this:
do
{
printf("Enter a number for x1 and x2");
scanf("%lf %lf", &x1, &x2);
}
if(f(x1)*f(x2)<0);
You have the start of a do...while
loop, but there's no while
condition. You also have an if
with no statement that follows. You probably wanted to use while
here instead of if
:
do
{
printf("Enter a number for x1 and x2");
scanf("%lf %lf", &x1, &x2);
}
while (f(x1)*f(x2)<0);
Upvotes: 1
Reputation: 104494
this:
if(f(x1)*f(x2)<0); /* **<--- if statement line 16** */
should be:
while (f(x1)*f(x2)<0); /* **<--- if statement line 16** */
Upvotes: 0
Reputation: 26066
Your do
loop:
do {
printf("Enter a number for x1 and x2");
scanf("%lf %lf", &x1, &x2);
}
is missing the closing while (...);
condition.
Probably you wanted to write while
instead of if
.
Upvotes: 1