[c++] Why is my power operator (^) not working?

#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?

This question is related to c++ c

The answer is


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;
}

Instead of using ^, use 'pow' function which is a predefined function which performs the Power operation and it can be used by including math.h header file.

^ This symbol performs BIT-WISE XOR operation in C, C++.

Replace a^i with pow(a,i).


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;
}
     

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


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.


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

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