Computer Science Canada

Not being able to use pow()

Author:  ihsh [ Mon Sep 06, 2010 8:42 pm ]
Post subject:  Not being able to use pow()

It's me again. Confused

I was trying to write the code of a binary converter. But I always got strange outputs so I tested my codes and found out that the problem was with the function pow ().
At first I thought it was a variable problem again, but it wasn't! I wrote a new program to test the function and the output was still zero.

code:

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

int main ()
{
        printf ("%d", pow(2,3));
        return (0);
}


Thanks for your time.

Author:  michaelp [ Mon Sep 06, 2010 8:50 pm ]
Post subject:  RE:Not being able to use pow()

The format specifier "%d" is for an integer, but the function "pow" returns a double.
So, changing %d to %f will then print "8.000000" (or something similar). Changing that to "%.f" will then just print out 8.
Also, using %d, you can use:
code:
printf("%d", (int)pow(2, 3) );

And you will also get 8.
Here is a list of format specifiers in C:
http://www.mekong.net/tech/printf.htm

Also, when I compiled this using GCC, I got the
code:
warning: format ?%d? expects type ?int?, but argument 2 has type ?double

Not sure if you got that when you compiled your code.

Author:  ihsh [ Mon Sep 06, 2010 9:20 pm ]
Post subject:  RE:Not being able to use pow()

Thanks, program works now. Smile
Quote:
Also, when I compiled this using GCC, I got the
code:
warning: format ?%d? expects type ?int?, but argument 2 has type ?double

Not sure if you got that when you compiled your code.


No I didn't get any warning when compiling the code.

Author:  DtY [ Tue Sep 07, 2010 3:41 pm ]
Post subject:  Re: RE:Not being able to use pow()

michaelp @ Mon Sep 06, 2010 8:50 pm wrote:
Also, when I compiled this using GCC, I got the
code:
warning: format ?%d? expects type ?int?, but argument 2 has type ?double

Not sure if you got that when you compiled your code.
I think that warning is only in pretty new versions of gcc.

e; Also, you should avoid using pow() unless the exponent rather large or a variable. a*a*a will be faster than pow(a,3).


: