我编写了一个“二等分方法”,但是它可以永远运行,请帮助我,非常感谢 我的代码只是找到x ^ 3 + 4 * x ^ 2-10的最接近根的简单方法,认为它将停止14次,但不是(我尝试将a和b设置为1和2)
void bis(double a, double b)
{
cout << fixed << setprecision(8);
double x = (a + b) / 2;
double result = pow(x, 3) + 4 * pow(x, 2) - 10;
int n = 0;
while (abs(result) > 0,0001) {
x = (a + b) / 2;
result = pow(x, 3) + 4 * pow(x, 2) - 10;
if (pow(a, 3) + 4 * pow(a, 2) - 10 > 0 && pow(b, 3) + 4 * pow(b, 2) - 10 < 0) {
n++;
if (result > 0) {
cout << n << " " << a << " " << b << " " << x << " " << result << endl;
a = x;
} else if (result < 0) {
cout << n << " " << a << " " << b << " " << x << " " << result << endl;
b = x;
}
}
if (pow(a, 3) + 4 * pow(a, 2) - 10 < 0 && pow(b, 3) + 4 * pow(b, 2) - 10 > 0) {
n++;
if (result > 0) {
cout << n << " " << a << " " << b << " " << x << " " << result << endl;
b = x;
} else if (result < 0) {
cout << n << " " << a << " " << b << " " << x << " " << result << endl;
a = x;
}
}
}
}