Data_Structure/作業/unit1/binary-search-square-root/test.c

45 lines
932 B
C
Raw Normal View History

2025-01-20 21:30:53 +08:00
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main() {
int x;
double precision = 1e-5;
printf("***<2A><><EFBFBD>Jx<4A><78>(x>0)<29>p<EFBFBD><EFBFBD><E2A5AD><EFBFBD><EFBFBD>***\n");
// <20>M<EFBFBD>ſ<EFBFBD><C5BF>J<EFBFBD>w<EFBFBD>İ<EFBFBD>
int c;
while ((c = getchar()) != '\n' && c != EOF);
// <20>ϥ<EFBFBD> fgets <20>M sscanf <20><>Ū<EFBFBD><C5AA><EFBFBD><EFBFBD><EFBFBD>J
char input[100];
if (fgets(input, sizeof(input), stdin) == NULL) {
printf("Ū<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>J<EFBFBD>ɵo<EFBFBD>Ϳ<EFBFBD><EFBFBD>~\n");
return 1;
}
if (sscanf(input, "%d", &x) != 1 || x <= 0) {
printf("<EFBFBD>L<EFBFBD>Ī<EFBFBD><EFBFBD><EFBFBD><EFBFBD>J<EFBFBD>C<EFBFBD>п<EFBFBD><EFBFBD>J<EFBFBD>@<40>ӥ<EFBFBD><D3A5><EFBFBD><EFBFBD>ơC\n");
return 1;
}
int lower = 0, upper = x;
double ans = sqrt(x);
double mid;
while (upper - lower > precision) {
mid = (lower + upper) / 2.0;
if (mid * mid > x) {
upper = mid;
} else {
lower = mid;
}
}
printf("%d<><64><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ڬ<EFBFBD>%f\n", x, mid);
printf("sqrt(%d)<29><><EFBFBD><EFBFBD><EFBFBD>G<EFBFBD><47>%f\n", x, ans);
return 0;
}