Search code examples
cnewtons-methoddifferentiation

Input a value for a scanf(), but nothing happens


I'm writing some code as part of a few assignment exercises to learn C programming from absolute basics, and I've run into a problem, which is probably quite simple to solve, but I'm completely stuck! I'm writing a program to implement a basic Newton's method for differentiation. Whenever I input an initial value to the scanf(), the program simply stops, doesn't return anything, terminate or freeze. Any help would be great. Here is my code to start with:

 #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;
};

Solution

  • In your while loop:

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

    the value of the = right operand is always the same, how could you exit the loop once you enter it?