Why is my power operator (^) not working?

2018-12-31 17:02发布

#include "stdio.h"
#include "math.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 =sum+result;
    }
    printf("%d\n",sum);
}

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

标签: c
7条回答
旧人旧事旧时光
2楼-- · 2018-12-31 17:11

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);
查看更多
梦寄多情
3楼-- · 2018-12-31 17:17

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.

查看更多
看淡一切
4楼-- · 2018-12-31 17:17

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

查看更多
查无此人
5楼-- · 2018-12-31 17:20

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

查看更多
看淡一切
6楼-- · 2018-12-31 17:27

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 );
查看更多
残风、尘缘若梦
7楼-- · 2018-12-31 17:31

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;
}
查看更多
登录 后发表回答