Untitled
unknown
plain_text
a month ago
935 B
4
Indexable
#include <stdio.h>
#include <math.h>
float f(float x) {
return x*x*x - x - 2;
}
int main() {
float x0, x1, x2, f0, f1, f2, error;
int i = 1;
printf("Enter first guess x0: ");
scanf("%f", &x0);
printf("Enter second guess x1: ");
scanf("%f", &x1);
printf("Enter tolerable error: ");
scanf("%f", &error);
f0 = f(x0);
f1 = f(x1);
if (f0 * f1 > 0) {
printf("Incorrect initial guesses.\n");
return 0;
}
do {
x2 = (x0 * f1 - x1 * f0) / (f1 - f0);
f2 = f(x2);
printf("Iteration %d: x = %f\n", i, x2);
if (fabs(f2) < error)
break;
if (f0 * f2 < 0) {
x1 = x2;
f1 = f2;
} else {
x0 = x2;
f0 = f2;
}
i++;
} while (1);
printf("\nApproximate root = %f\n", x2);
return 0;
}Editor is loading...
Leave a Comment