45 lines
932 B
C
45 lines
932 B
C
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <math.h>
|
|
|
|
int main() {
|
|
int x;
|
|
double precision = 1e-5;
|
|
|
|
printf("***輸入x值(x>0)計算平方根***\n");
|
|
|
|
// 清空輸入緩衝區
|
|
int c;
|
|
while ((c = getchar()) != '\n' && c != EOF);
|
|
|
|
// 使用 fgets 和 sscanf 來讀取輸入
|
|
char input[100];
|
|
if (fgets(input, sizeof(input), stdin) == NULL) {
|
|
printf("讀取輸入時發生錯誤\n");
|
|
return 1;
|
|
}
|
|
|
|
if (sscanf(input, "%d", &x) != 1 || x <= 0) {
|
|
printf("無效的輸入。請輸入一個正整數。\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的平方根為%f\n", x, mid);
|
|
printf("sqrt(%d)的結果為%f\n", x, ans);
|
|
|
|
return 0;
|
|
}
|