-2

Here is the code that I couldn't figure out why it's not working (I'm always getting a result like 0.000000):

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

int main ()
{
    double num,b;
    printf("Write a number between 0 and 256"); scanf("%lf",&num);
    num = pow(2.0,b);
    printf("%lf",b);    
    return 0 ;
}

Here, the answer of the pow is known as num since it's introduced by user, and I'm trying to find the value of b which is inside the function!

Actually, I saw similar questions here, but some of them were dependent on a solution of gcc, (I'm using Dev C++) and the rest had a structure which is slightly different and the problem may arise due to this difference.

Mohit Jain
  • 30,259
  • 8
  • 73
  • 100
Ut.Son
  • 9
  • 1
  • 7
    `b` is not initialized. Thus, your code exhibits Undefined Behavior. – Spikatrix Mar 31 '15 at 14:07
  • 2
    "Here, the answer of the pow is known as num since it's introduced by user, and i'm trying to find the value of b which is inside the function!" makes no sense to me – Spikatrix Mar 31 '15 at 14:07
  • 1
    You're storing the inputted value in num and then overwriting it with 2 to the power of undefined. – teppic Mar 31 '15 at 14:13

4 Answers4

7

You probably meant

b = pow(2.0, num);

at the seventh line. As the reference says, the prototype of the pow method is:

double pow (double base, double exponent);

So you will get the calculated result returned from the given in parameters.

If you actually meant that you are looking for the base 2 logarithm, then you should use logarithm:

b = log2(num);

This works in C99 using the <tgmath.h> header, or you can use the solution in @SleuthEye's answer

The header include also has a typo, as @Paul R commented.

Community
  • 1
  • 1
meskobalazs
  • 15,741
  • 2
  • 40
  • 63
  • Thank you guys, i still need a time to think as a programmer :) That's why i insisted on using 'pow' where i could be used 'log' perfectly. – Ut.Son Apr 01 '15 at 11:08
2

To get the value of b for which pow(2.0,b) == num, you should use logarithms (which is related to the inverse of pow) to obtain:

b = log(num)/log(2.0);
SleuthEye
  • 14,379
  • 2
  • 32
  • 61
1

C is not math. It will not try to find the value of b for you. You're actually passing its value(which contains garbage) as a parameter, and storing the undefined result of pow() in num, overwriting whatever was that you read in there. Then, you display the undefined value of b, witch is zero probably because you're in debug mode.

For your purposes, try using log().

Not a real meerkat
  • 5,604
  • 1
  • 24
  • 55
0

You should initialize b. You used #include<math.h.> , which's wrong. Try #include<math.h>.

ForceBru
  • 43,482
  • 10
  • 63
  • 98
icecity96
  • 1,177
  • 12
  • 26