Data_Structure/作業/unit1/binary-search-solves-equation/test_1.c
2025-01-20 21:30:53 +08:00

50 lines
997 B
C
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include <stdio.h>
#include <math.h>
#define EPSILON 1e-6
#define MAX_ITERATIONS 100
double f(double x, double a) {
return x * x - a;
}
double bisection_method(double a, double left, double right) {
double mid;
int iterations = 0;
while (right - left > EPSILON && iterations < MAX_ITERATIONS) {
mid = (left + right) / 2;
if (f(mid, a) == 0.0) {
return mid;
} else if (f(mid, a) * f(left, a) < 0) {
right = mid;
} else {
left = mid;
}
iterations++;
}
return (left + right) / 2;
}
int main() {
double a, result;
printf("請輸入一個正數 a 來求解 x^2 = a: ");
scanf("%lf", &a);
if (a < 0) {
printf("錯誤a 必須是非負數\n");
return 1;
}
result = bisection_method(a, 0, a > 1 ? a : 1);
printf("方程 x^2 = %.6f 的解約為 x = %.6f\n", a, result);
printf("驗證:%.6f^2 = %.6f\n", result, result * result);
return 0;
}