Lalit Chattar
Lalit Chattar

Reputation: 1984

code blocks power function is not working in c

i am using code block for learning c. my code is

#include<stdio.h>
#include<math.h>
int main()
{
  int x;
  x = pow(5,2);
  printf("%d", x);
}

Output is 25

When i am using this code

#include<stdio.h>
#include<math.h>
int main()
{
  int x,i,j;
  printf("please enter first value");
  scanf("%d", &i);//5
  printf("please enter second value");//2
  scanf("%d", &j);
  x = pow(i,j);
  printf("%d", x);
}

Output is 24

what is wrong here? i am just taking value using scan function and also using pow function in a same way.

Upvotes: 1

Views: 6216

Answers (5)

Ashok Shah
Ashok Shah

Reputation: 956

Using your code i got result 25 which is correct. Although Try changing the data type of result such as float or double.

Upvotes: 0

hyde
hyde

Reputation: 62797

Try changing initialization to this:

int x=-1 ,i=-1 ,j=-1;

And last print to this:

printf("pow(%d, %d) == %d\n", i, j, x);

That should give good hint about the problem. Also, check return values of scanf, they should return number of items read, ie. 1 with code above.

It's almost certain, that you entered invalid input for scanf, and i or j were left uninitialized, and that 24 is just garbage value.

Also, compile with warnings enabled, and fix them (like, add return 0; to end of main).

Upvotes: 2

Daniel Fischer
Daniel Fischer

Reputation: 183888

I suspect you have a naive implementation of pow in your libm (I get 25, as it should be). If that computes pow(x,y) as exp(y*log(x)) for positive x without checking for (small) integral exponents and treating them specially, you get

Prelude> 2 * log 5
3.2188758248682006
Prelude> exp it
24.999999999999996

a double result slightly smaller than 25, so when that is converted to int it is truncated to 24.

To check, assign the result of pow(i,j) to a double and print that out.

With hardcoded pow(5,2), the compiler (most likely, it's what gcc does even without optimisation) computes the result during compilation exactly.

Upvotes: 8

Mihai8
Mihai8

Reputation: 3147

It seems that there is nothing wrong with the second program, except that you must add at the end

return 0;

If you read the value j with 2 then the result will be just 25.

Upvotes: 0

pochen
pochen

Reputation: 873

Your code correctly gives 25 on my windows x64.

You probably needs to run it again see if you just read it wrong...
The missing "return 0;" is not the problem here.

If, anything, could ever go wrong,
you can try adding

fflush(stdin);//or out

after very scanf and printf. If any of the flushes solves your problem, you know what is going wrong.

Upvotes: 1

Related Questions