62
#include <stdio.h>

void main(void)
{
    int a;
    int result;
    int sum = 0;
    printf("Enter a number: ");
    scanf("%d", &a);
    for( int i = 1; i <= 4; i++ )
    {
        result = a ^ i;

        sum += result;
    }
    printf("%d\n", sum);
}

Why is ^ not working as the power operator?

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
Abid Ali
  • 1,731
  • 8
  • 26
  • 62
  • Works fine for me after I replace the return value of main() with "int". I didn't expect it to work, though, as `` and `` are usually used instead of `"stdio.h"` and `"math.h"`. But it looks like GCC doesn't really care. – Sergei Tachenov Jan 30 '11 at 14:18
  • 8
    @Abid It's often good to edit questions, but in this case the edits have made the question meaningless (you have replaced the problem with the solution). It's better to leave the original questions so others can learn - but it's now just confusing (There is no "^" in the question). Suggest you revert to the last edit that makes sense as a question – peter.murray.rust Jan 30 '11 at 14:25
  • 8
    Changed back to using `^` since the question (and answers) make little sense otherwise. Since peoro answered correctly for your question, you should accept it and move on. If you have _another_ question, then please ask another question. Don't edit this one to make all the work done meaningless. – paxdiablo Jan 30 '11 at 14:30
  • @sergey Tchenov.. how did your program worked?? please explain – Abid Ali Jan 30 '11 at 14:34
  • @Abid, I typed "1" and got "4", typed "10" and got "11110", exactly as one would expect from the code. But I have used a different compiler which apparently doesn't have problems with pow() overloads. – Sergei Tachenov Jan 30 '11 at 14:41
  • @Sergey Tachenov: Which compiler exactly...? –  Jan 30 '11 at 14:44
  • @Øystein, I tested it with GCC and G++, version 4.5.0, MinGW port, and GCC/G++ 4.2.4 under Ubuntu 8.04. For GCC, I had to add `-std=c99 -lm`, with G++ it just worked. – Sergei Tachenov Jan 30 '11 at 14:50
  • 1
    @Sergey Tachenov: Oh, I see now that you used pow()? I thought you got the OP's original code (with ^ for pow) to work. –  Jan 30 '11 at 15:04
  • @Øystein, of course. The question at some point was edited to use pow() and that was my comment to it. Then it got edited back as it made no sense in the second edition. – Sergei Tachenov Jan 30 '11 at 15:38

11 Answers11

92

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.

Sergei Tachenov
  • 24,345
  • 8
  • 57
  • 73
66

In C ^ is the bitwise XOR:

0101 ^ 1100 = 1001 // in binary

There's no operator for power, you'll need to use pow function from math.h (or some other similar function):

result = pow( a, i );
peoro
  • 25,562
  • 20
  • 98
  • 150
  • i used that function.. but :/ it`s giving an error that ambiguous call to the overloaded function.. – Abid Ali Jan 30 '11 at 14:05
  • @Abid Ali: can you post the whole error and your code with `pow`? – peoro Jan 30 '11 at 14:06
  • 3
    @Abid Ali: you need to include math.h. Put this line at the beginning of your file: `#include ` – peoro Jan 30 '11 at 14:09
  • @Abid Ali: sorry, I missed it. can you post the error message also? – peoro Jan 30 '11 at 14:11
  • this is the error message : pow': ambiguous call to overloaded function – Abid Ali Jan 30 '11 at 14:18
  • @Abid Ali: I don't know. Your code should work fine in C99 and in C++98 (except for `main` which should return an `int`). My guess is that you're using a broken/non-standard compiler. – peoro Jan 30 '11 at 14:22
  • @Abid, that means you use a C++ compiler (C doesn't have overloaded functions), so your question should be tagged C++, not C. I have no idea why it doesn't work, though. – Sergei Tachenov Jan 30 '11 at 14:24
  • broken / non standard compiler.. what does it mean? – Abid Ali Jan 30 '11 at 14:25
  • @peoro, judging by the error message it's the Microsoft compiler. What I don't understand is why it doesn't work with two ints when [MSDN says that there is an (int, int) version](http://msdn.microsoft.com/en-us/library/dt5dakze%28v=vs.71%29.aspx). – Sergei Tachenov Jan 30 '11 at 14:26
  • @Sergey Tachenov: from C99 there's `tgmath.h` which offers _overloaded_ macros for math functions. So I wouldn't be so sure it's C++. About the error, wouldn't know. – peoro Jan 30 '11 at 14:29
  • 1
    @Abid Ali: the _program_ you're using to write and compile your C code doesn't follow the standard of C: it can't compile valid C code. Don't know why. I would suggest you to switch to a more standard compliant compiler. If you are using windows try to download and write your programs in Dev-C++ (for example), which uses GCC as compiler. Cannot help you find out why that code doesn't work with microsoft studio. – peoro Jan 30 '11 at 14:31
  • 1
    @peoro, overloaded macros? Macros aren't typed, they accept anything. And C can't possibly have overloaded functions since there is no name mangling. About the error, some googling shows that a workaround is to cast one of the arguments to double like `(int) pow((double) a,i)` - I cast the result too as it returns double, not int. – Sergei Tachenov Jan 30 '11 at 14:33
  • @Sergey Tachenov: macros you can write do not, but tgmath.h macros do. http://pubs.opengroup.org/onlinepubs/009695399/basedefs/tgmath.h.html This is probably the thing I like the less in C99. – peoro Jan 30 '11 at 14:35
  • ;/ what to do now? except download DEV C++ – Abid Ali Jan 30 '11 at 14:36
  • 2
    @Abid Ali: try to replace that line with this one: `pow( (double)a, (double)i );` – peoro Jan 30 '11 at 14:37
  • @Abid Ali: glad to hear that. Also read the other answers: will let you understand why it wasn't working until now. – peoro Jan 30 '11 at 14:43
3

First of all ^ is a Bitwise XOR operator not power operator.

You can use other things to find power of any number. You can use for loop to find power of any number

Here is a program to find x^y i.e. xy

double i, x, y, pow;

x = 2;
y = 5; 
pow = 1;
for(i=1; i<=y; i++)
{
    pow = pow * x;
}

printf("2^5 = %lf", pow);

You can also simply use pow() function to find power of any number

double power, x, y;
x = 2;
y = 5;
power = pow(x, y); /* include math.h header file */

printf("2^5 = %lf", power);
Pankaj Prakash
  • 2,300
  • 30
  • 31
3

pow() doesn't work with int, hence the error "error C2668:'pow': ambiguous call to overloaded function"

http://www.cplusplus.com/reference/clibrary/cmath/pow/

Write your own power function for ints:

int power(int base, int exp)
{
    int result = 1;
    while(exp) { result *= base; exp--; }
    return result;
}
Max
  • 105
  • 5
  • `int`s should be automatically promoted to `double`s, shouldn't they? Your link is about C++, anyway. – peoro Jan 30 '11 at 14:32
  • Since this function accepts floats and doubles, when you call it with ints, it doesn't know to what type it should promote ints. – Max Jan 30 '11 at 14:34
  • "Your link is about C++, anyway." But the poster is using C++ compiler, since he has an error because of overloading. – Max Jan 30 '11 at 14:35
  • This is suboptimal in several ways. First you're going to run the loop the number of times given in exp. Depending on the size of int this may be quite a lot. However the largest exponent that makes sense is pow(2, sizeof(int)*CHAR_BIT-1). But there's more room for improvement. pow(x, y) == pow(2, n) * pow(x', r). The term pow(2,n) can be implemented by simple bit shift by n. Determining x' and r may be faster than iterating that loop. – datenwolf Jan 30 '11 at 15:08
  • I've given the simplest implementation as an example, as shown in algorithm textbooks. – Max Jan 30 '11 at 15:12
  • See [Addition Chain Exponentiation](https://en.wikipedia.org/wiki/Addition-chain_exponentiation) — Wikipedia – Craig McQueen Apr 29 '19 at 23:29
2

include math.h and compile with gcc test.c -lm

anup
  • 529
  • 5
  • 14
2

It's not working because c as well as c++ do not have any operators to perform power operations.

What you can do is, you can use math.h library and use pow function. There is a Function for this instead of the operator.

`   #include<stdio.h>
    #include<math.h>
    int main(){
        int base = 3;
        int power = 5;
        pow(double(base), double(power));
        return 0;
     }`
1

You actually have to use pow(number, power);. Unfortunately, carats don't work as a power sign in C. Many times, if you find yourself not being able to do something from another language, its because there is a diffetent function that does it for you.

Nick Anderegg
  • 1,006
  • 1
  • 12
  • 25
  • 8
    Carets do "work", they just don't do what you might expect them to. –  Jan 30 '11 at 14:08
  • 1
    Well, they don't work for powers, a function is needed for that. But the user who posed the question said his caret wasn't working, to which I replied that particular methodology doesn't work in C. But valid point, I'll edit. – Nick Anderegg Jan 30 '11 at 14:11
1

There is no way to use the ^ (Bitwise XOR) operator to calculate the power of a number. Therefore, in order to calculate the power of a number we have two options, either we use a while loop or the pow() function.

1. Using a while loop.

#include <stdio.h>

int main() {

    int base, expo;
    long long result = 1;

    printf("Enter a base no.: ");
    scanf("%d", &base);

    printf("Enter an exponent: ");
    scanf("%d", &expo);

    while (expo != 0) {
        result *= base;
        --expo;
    }

    printf("Answer = %lld", result);
    return 0;
}    
             

2. Using the pow() function

#include <math.h>
#include <stdio.h>

int main() {

    double base, exp, result;

    printf("Enter a base number: ");
    scanf("%lf", &base);

    printf("Enter an exponent: ");
    scanf("%lf", &exp);

    // calculate the power of our input numbers
    result = pow(base, exp);

    printf("%.1lf^%.1lf = %.2lf", base, exp, result);

    return 0;
}
     
RockFrenzy
  • 1,585
  • 3
  • 11
  • 13
1

If you are trying to calculate the power of base 2, you can use the bitwise shift operator to calculate the power. For example, say you wanted to calculate 2 to the power of 8.

2 << 7
Nasik Shafeek
  • 951
  • 8
  • 17
0

For integer exponent, you may simply write your implementation of pow()

int myPow(int x, int n)
{
  if (n == 0) return 1;
  return x * myPow(x, n - 1);
}
mwck46
  • 148
  • 9
  • the question is `Why is my power operator (^) not working?` and this doesn't explain why. It's also far worse than [Exponentiation by squaring](https://en.wikipedia.org/wiki/Exponentiation_by_squaring) – phuclv Jun 26 '22 at 02:42
0

All the solutions here, except for the ones that use math.h will not work for fractional powers.

The last example here is by far the worst and acctually copy'n'paste. It is not only slow but it will break stuff at some point. Just use the math.h with pow() as already stated and that's good enough. If you are not allowed to use math.h, use a tail-recursive function, that saves the current operation result in an accumulator and returns the accumulator at the end, thus avoiding exploding function calls due to extensive traces.

NicoDorn
  • 31
  • 4