-1

我正在编写一些代码作为从绝对基础学习 C 编程的一些作业练习的一部分,我遇到了一个问题,这可能很容易解决,但我完全卡住了!我正在编写一个程序来实现基本的牛顿微分方法。每当我向 scanf() 输入初始值时,程序就会停止,不返回任何内容,终止或冻结。任何帮助都会很棒。这是我的代码开始:

 #include <stdio.h>
    #include <stdlib.h>
    #include <math.h>

//function to be used f(x) = cos(x)-x^3

//f'(x) = -sin(x)-3x^2

int main()
{
  double x, xold;
  printf("Enter an initial value between 0 and 1\n");
  scanf("%lf",&xold);
  double eps = 1e-12;
   x = xold - ((cos(xold)-pow(xold,3))/(-(sin(xold)-(3*pow(xold,2)))));
    while (fabs(x-xold)>eps)
    {
    x = xold - ((cos(xold)-pow(xold,3))/(-sin(xold)-(3*pow(xold,2))));
    }
    printf("The answer is %.12lf",x);
    return 0;
};
4

2 回答 2

2

在您的 while 循环中:

x = xold - ((cos(xold)-pow(xold,3))/(-sin(xold)-(3*pow(xold,2))));

右操作数的值=总是相同的,一旦进入循环,你怎么能退出循环呢?

于 2014-07-04T19:47:21.570 回答
0

实际上问题是你没有更新你的xold变量。尝试以下修改后的代码来解决您的问题,看看我是否做得正确:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>


int main()
{
    double x, xold;
    printf("Enter an initial value between 0 and 1\n");
    scanf("%lf",&x);
    double eps = 1e-12;

    x = x - ((cos(x)-pow(x,3))/(-(sin(x)-(3*pow(x,2)))));
    while (fabs(x - xold)>eps)
    { 
        xold = x;
        x = x - ((cos(x)-pow(x,3))/(-sin(x)-(3*pow(x,2))));
    }
    printf("The answer is %.12lf\n",x);

    return 0;
}
于 2014-07-04T20:09:28.267 回答