-1

I were asked to c-program to accept two variables and print the answer when second variable is raised to the power of first variable. So I coded,

#include<stdio.h>
#include<math.h> 
int x,y;

int main()
{
scanf("%d %d",&x,&y);
printf("%d",pow(x,y));
}

It should be working right? But it doesn't! So I done

#include<stdio.h>
#include<math.h> 
int x,y;

int main()
{
scanf("%d %d",&x,&y);
int u=pow(x,y);
printf("%d",u);
}

Then it worked. i.e for the inputs like x=10 y=3

the output for the first snippet, was 11829309 something I don't remember.

But the second one results correctly as 1000.

Please, tell why this happened?

  • 5
    Typo: `printf("%d", pow(x,y));` ==> `printf("%f\n", pow(x,y));` Unlike the type conversion in `int u=pow(x,y);` the variadic functions like `printf` must be given the correct type. – Weather Vane Feb 20 '22 at 11:05
  • 4
    Because `pow` return a `double` and this is converted if you assign to `int` while it is not if you pass it to a variadic function. – Gerhardh Feb 20 '22 at 11:06
  • or, for this simple test case (normally prefer other options), `printf("%d\n", (int)pow(x, y));` – pmg Feb 20 '22 at 11:07
  • Aside, with integer values you would be advised to do `(int)round(pow(x, y))` – Weather Vane Feb 20 '22 at 11:09
  • 2
    Unrelated: no reason for `x` and `y` to be global variables. Define them inside `main()` instead (as local variables). – pmg Feb 20 '22 at 11:09

1 Answers1

0

pow returns a double, therefore causing undefined behavior because you pass it to a format string expecting an int, since typeof(pow(int,int)) == double.

Try

printf("%lf\n", pow(3,5));

or use an explicit cast, like

printf("%d\n", (int)pow(3,5));

You're trying to print that double value with the %d conversion specifier: printf("%d",pow(x,y));

which expects an int value, but provides a double.

NoobCoder
  • 513
  • 3
  • 18
  • @pmg I just wanted to state a general problem. Doesn't matter if you divide it and save as a float or save as a double while using pow, the explicit cast is required. But thanks, i've edited it. – NoobCoder Feb 20 '22 at 11:15