-3

How do I calculate a power in C, and do you have to include anything? I have tried to include math.h, however it didn't work. What is de difference between a int and a double in this case.

  • 1
    Welcome to Stack Overflow! You could take the [tour](http://stackoverflow.com/tour) to have a global idea of how this site works, and read the [advice on how to ask](http://stackoverflow.com/help/asking) in the help center to see what questions are welcomed here and which are not. – Eregrith May 11 '15 at 14:48

2 Answers2

2

To calculate a power in C, the best way is to use the function pow(). It takes two double arguments: the first is the number that will be raised by the power, and the second argument is the power amount itself.

So: double z = pow(double x, double y);

Then the result will be saved into the double z. You will have to use the math.h library in order to use this function.

Dada
  • 6,313
  • 7
  • 24
  • 43
supdun
  • 81
  • 2
  • Actually, `pow` is not always the "best way". Most of the time it's the right way, but if the power you're raising to — `y` — is a small, constant integer like 2 or 3, sometimes it't better to just multiply `x` by itself. See also [this question](https://stackoverflow.com/questions/9704195). – Steve Summit Apr 26 '22 at 11:55
1
#include <stdio.h>
int main()
{
  int base, exp;
  long long int value=1;
  printf("Enter base number and exponent respectively: ");
  scanf("%d%d", &base, &exp);
  while (exp!=0)
  {
      value*=base;  /* value = value*base; */
      --exp;
  }
  printf("Answer = %d", value);
}