Why is my power operator (^) not working?

前端 未结 8 1330
半阙折子戏
半阙折子戏 2020-11-22 02:12
#include 

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


        
相关标签:
8条回答
  • 2020-11-22 02:44

    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);
    
    0 讨论(0)
  • 2020-11-22 02:56

    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 );
    
    0 讨论(0)
  • 2020-11-22 02:57

    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.

    0 讨论(0)
  • 2020-11-22 02:57

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

    0 讨论(0)
  • 2020-11-22 02:58

    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.

    0 讨论(0)
  • 2020-11-22 03:01

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

    0 讨论(0)
提交回复
热议问题