#include <stdio.h>
#include <math.h>
// 方程式 f(x) を定義
double f(double x, int n) {
return pow(x
, n
) - 7.0; // f(x) = x^n - 7 }
// 二分法の実装
double nibun(double a, double b, double gosa, int n) {
double m;
while (fabs(b
- a
) > gosa
) { m = (a + b) / 2.0;
if (fabs(f
(m
, n
)) < gosa
) { // f(m) が十分小さい場合 break;
} else if (f(a, n) * f(m, n) < 0.0) {
b = m;
} else {
a = m;
}
}
return m;
}
int main() {
int n;
double a = 1.0, b = 3.0, gosa = 1e-8; // 初期区間と許容誤差
// n を入力
printf("自然数 n を入力してください (7^(1/n) を計算): ");
// 二分法で解を計算
double root = nibun(a, b, gosa, n);
// 結果を表示
printf("7^(1/%d) の近似解: %.8lf\n", n
, root
);
return 0;
}
I2luY2x1ZGUgPHN0ZGlvLmg+CiNpbmNsdWRlIDxtYXRoLmg+CgovLyDmlrnnqIvlvI8gZih4KSDjgpLlrprnvqkKZG91YmxlIGYoZG91YmxlIHgsIGludCBuKSB7CiAgICByZXR1cm4gcG93KHgsIG4pIC0gNy4wOyAvLyBmKHgpID0geF5uIC0gNwp9CgovLyDkuozliIbms5Xjga7lrp/oo4UKZG91YmxlIG5pYnVuKGRvdWJsZSBhLCBkb3VibGUgYiwgZG91YmxlIGdvc2EsIGludCBuKSB7CiAgICBkb3VibGUgbTsKICAgIHdoaWxlIChmYWJzKGIgLSBhKSA+IGdvc2EpIHsKICAgICAgICBtID0gKGEgKyBiKSAvIDIuMDsKICAgICAgICBpZiAoZmFicyhmKG0sIG4pKSA8IGdvc2EpIHsgLy8gZihtKSDjgYzljYHliIblsI/jgZXjgYTloLTlkIgKICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgfSBlbHNlIGlmIChmKGEsIG4pICogZihtLCBuKSA8IDAuMCkgewogICAgICAgICAgICBiID0gbTsKICAgICAgICB9IGVsc2UgewogICAgICAgICAgICBhID0gbTsKICAgICAgICB9CiAgICB9CiAgICByZXR1cm4gbTsKfQoKaW50IG1haW4oKSB7CiAgICBpbnQgbjsKICAgIGRvdWJsZSBhID0gMS4wLCBiID0gMy4wLCBnb3NhID0gMWUtODsgLy8g5Yid5pyf5Yy66ZaT44Go6Kix5a656Kqk5beuCgogICAgLy8gbiDjgpLlhaXlipsKICAgIHByaW50Zigi6Ieq54S25pWwIG4g44KS5YWl5Yqb44GX44Gm44GP44Gg44GV44GEICg3XigxL24pIOOCkuioiOeulyk6ICIpOwogICAgc2NhbmYoIiVkIiwgJm4pOwoKICAgIC8vIOS6jOWIhuazleOBp+ino+OCkuioiOeulwogICAgZG91YmxlIHJvb3QgPSBuaWJ1bihhLCBiLCBnb3NhLCBuKTsKCiAgICAvLyDntZDmnpzjgpLooajnpLoKICAgIHByaW50ZigiN14oMS8lZCkg44Gu6L+R5Ly86KejOiAlLjhsZlxuIiwgbiwgcm9vdCk7CgogICAgcmV0dXJuIDA7Cn0K