Question

I write a C code that have power function that is from math.h library. when I compiled my program, I received an error which is " undefined reference to 'pow' function ", I compile my program using gcc compiler (fedora 9).

I insert -lm flag to gcc then, the error is omitted but the output of the pow function is 0.

#include<math.h>
main()
{
double a = 4, b = 2;
b = pow(b,a);
}

Can anyone help me? Is there is a problem in my compiler??

Thanks.

Was it helpful?

Solution

Your program doesn't output anything.

The 0 you are referring to is probably the exit code, which will be 0 if you don't explicitly return from main.

Try changing it to a standards-compliant signature and return b:

int main(void) {
  ...
  return b;
}

Note that the return values is essentially limited to 8 bits-worth of information, so very, very limited.

Use printf to display the value.

#include <stdio.h>
...
  printf("%f\n", b);
...

You must use a floating point conversion specifier (f, g or e) to print double values. You cannot use d or others and expect consistent output. (This would in fact be undefined behavior.)

OTHER TIPS

For everyone else who seek such an answer:

This will not work:

gcc my_program.c -o my_program

It will produce something like this:

/tmp/cc8li91s.o: In function `main':
my_program.c:(.text+0x2d): undefined reference to `pow'
collect2: ld returned 1 exit status

This will work:

gcc my_program.c -o my_program -lm

You are lacking the printf line to print the value to stdout. Try this one:

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

int main() {
        double a=4, b=2, c;

        c = pow(b,a);
        printf("%g^%g=%g\n", a,b,c);
        return 0;
}

The output will be:

4^2=16

There is confusion here regarding base and exponent. This is not immediately apparent because both 2^4 and 4^2 equal 16.

void powQuestion()
{
    double a, b, c;

    a = 4.0;
    b = 2.0;
    c = pow(b, a);

    printf("%g ^ %g = %g\n", a,b,c);        // Output: 4 ^ 2 = 16

    a = 9.0;
    b = 2.0;
    c = pow(b, a);

    printf("%g ^ %g = %g\n", a,b,c);        // Output: 9 ^ 2 = 512  >> Wrong result; 512 should be 81 <<


    // K & R, Second Edition, Fifty Second Printing, p 251: pow(x,y) x to the y

    double x, y, p;

    x = 9.0;
    y = 2.0;
    p = pow(x, y);

    printf("%g ^ %g = %g\n", x, y, p);      // Output: 9 ^ 2 = 81


    // even more explicitly

    double base, exponent, power;

    base = 9.0;
    exponent = 2.0;
    power = pow(base, exponent);

    printf("%g ^ %g = %g\n", base, exponent, power);    // Output: 9 ^ 2 = 81
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top