Abid Ali Abid Ali - 4 months ago 46
C Question

Why is my power operator (^) not working?

#include "stdio.h"
#include "math.h"

void main(void)
int a;
int result;
int sum=0;
printf("Enter a Number : ");
for(int i=1;i<=4;i++)
result = a^i;

sum =sum+result;

I don't know why this '^' is not working as power. Please help.


Well, first off, the ^ operator in C/C++ is the bit-wise XOR. It has nothing to do with powers.

Now, regarding your problem with using the pow() function, some googling shows that casting one of the arguments to double helps:

result = (int) pow((double) a,i);

Note that I also cast the result to int as all pow() overloads return double, not int. I don't have a MS compiler available so I couldn't check the code above, though.

Since C99, there are also float and long double functions called powf and powl respectively, if that is of any help.