我已经为大学班级编写了一份代码。代码应该是执行牛顿方法,通过输入起点和极限来找到方程的根(至少非常接近)。代码编译但在我输入必要的数据后,程序完成而不做任何其他事情!我在这里先向您的帮助表示感谢!这是代码:
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <math.h>
double f(double x)
{
return 4 * log10(x - 1) + 3 * pow(x,2);
}
double der_f (double x)
{
return 4 / (x - 1) + 6 * x;
}
int main()
{
assert(f(2) == 12);
assert(der_f(2) == 16);
double x;
double e;
printf("Please give the initial estimation of the root(bigger than one) (x(0)) as well as the limit(e)\n");
scanf("%lf %lf", &x, &e);
while (x <= 1)
{
printf("Please give the initial estimation of the root(bigger than one)(x(0))\n");
scanf("%lf", &x);
}
int n = 1;
while (fabs(f(x)) < e)
{
x = x - f(x) / der_f(x);
n ++;
printf("x(%d) = %lf\t", n, x);
}
return 0;
}
P.S:代码一直运行到第27行
答案 0 :(得分:1)
fabs(f(x)) < e
应为fabs(f(x)) > e
。你想在函数的值太远而不是零的时候继续运行。