#include <stdio.h>
#include <math.h>
// 方程式 f(x) を定義
double f(double x) {
return x * x - 7.0; // f(x) = x^2 - 7
}
// 二分法の実装
double nibun(double a, double b, double gosa) {
double m;
while (fabs(b
- a
) > gosa
) { m = (a + b) / 2.0;
if (fabs(f
(m
)) < gosa
) { // f(m) == 0 ではなく、誤差を考慮 break;
} else if (f(a) * f(m) < 0.0) {
b = m;
} else {
a = m;
}
}
return m;
}
int main() {
double a = 2.5, b = 2.7, gosa = 1e-8; // 初期区間と許容誤差
// 二分法で解を計算
double root = nibun(a, b, gosa);
// 結果を表示
printf("7^(1/2) の近似解: %.8lf\n", root
);
return 0;
}
I2luY2x1ZGUgPHN0ZGlvLmg+CiNpbmNsdWRlIDxtYXRoLmg+CgovLyDmlrnnqIvlvI8gZih4KSDjgpLlrprnvqkKZG91YmxlIGYoZG91YmxlIHgpIHsKICAgIHJldHVybiB4ICogeCAtIDcuMDsgLy8gZih4KSA9IHheMiAtIDcKfQoKLy8g5LqM5YiG5rOV44Gu5a6f6KOFCmRvdWJsZSBuaWJ1bihkb3VibGUgYSwgZG91YmxlIGIsIGRvdWJsZSBnb3NhKSB7CiAgICBkb3VibGUgbTsKICAgIHdoaWxlIChmYWJzKGIgLSBhKSA+IGdvc2EpIHsKICAgICAgICBtID0gKGEgKyBiKSAvIDIuMDsKICAgICAgICBpZiAoZmFicyhmKG0pKSA8IGdvc2EpIHsgLy8gZihtKSA9PSAwIOOBp+OBr+OBquOBj+OAgeiqpOW3ruOCkuiAg+aFrgogICAgICAgICAgICBicmVhazsKICAgICAgICB9IGVsc2UgaWYgKGYoYSkgKiBmKG0pIDwgMC4wKSB7CiAgICAgICAgICAgIGIgPSBtOwogICAgICAgIH0gZWxzZSB7CiAgICAgICAgICAgIGEgPSBtOwogICAgICAgIH0KICAgIH0KICAgIHJldHVybiBtOwp9CgppbnQgbWFpbigpIHsKICAgIGRvdWJsZSBhID0gMi41LCBiID0gMi43LCBnb3NhID0gMWUtODsgLy8g5Yid5pyf5Yy66ZaT44Go6Kix5a656Kqk5beuCgogICAgLy8g5LqM5YiG5rOV44Gn6Kej44KS6KiI566XCiAgICBkb3VibGUgcm9vdCA9IG5pYnVuKGEsIGIsIGdvc2EpOwoKICAgIC8vIOe1kOaenOOCkuihqOekugogICAgcHJpbnRmKCI3XigxLzIpIOOBrui/keS8vOinozogJS44bGZcbiIsIHJvb3QpOwoKICAgIHJldHVybiAwOwp9Cg==