50 lines
997 B
C
50 lines
997 B
C
#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;
|
||
}
|