简体   繁体   中英

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.

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.

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 ).

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM