-1

I don't know why this program does not work. It's C language. In Unix, it showed that "undefined reference to log" Could anyone help me figure out the bug and tell me how to fix it?

picture of the code below

Or:

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

int main()
{
  double x0, x1=4, x2=5, y0, sta=10, error = 0.00001, base = 2;
  do
  {
    x0 = (x1 + x2) / 2;
    y0 = (x0) * (log(x0))/(log(base));
    if ( y0 > sta )
    {
      x2 = x0;
    }else{
      x1 = x0;
    }
  }while(y0 > error);
  printf("%lf", x0);

  return 0;
}

(Beware transcription errors! I hope there are none.)

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Bruce
  • 23
  • 1
  • 6

1 Answers1

3

You have to link to the math library.

  user@x:~/src$ 
  user@x:~/src$ gcc -Wall file_that_uses_math_library.c -o bin -lm

This should solve your problem. It wasn't finding the log() function because the code wasn't linked when it was compiled.


Edit: You mentioned that "nothing prints out" in a comment to this answer. That is because your code is wrong and contains errors. The condition y0 > error is never satisfied and so the loop is infinite. If you take the call to printf() and place it inside of the loop you will see that the loop never ends and the same value gets printed out over and over.

If you compile/run this code you will see that the value of y0 is always 10 and is never less than .000001

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

int main()
{
  double x0, x1=4, x2=5, y0, sta=10, error = 0.00001, base = 2;
  do
  {
    x0 = (x1 + x2) / 2;
    y0 = (x0) * (log(x0))/(log(base));
    if ( y0 > sta )
    {
      x2 = x0;
    }else{
      x1 = x0;
    }

  printf("%lf is not less than %f\n", y0, error);

  }while(y0 > error);
  return 0;
}

You might benefit from learning how to use the GNU Debugger, because by setting a breakpoint on main, typing the command next once and simply holding return you would see that your program never leaves the loop. I'm not going to put the output of that into this post simply because it would be quite long.

Charles D Pantoga
  • 4,307
  • 1
  • 15
  • 14