Why is my power operator (^) not working?

前端 未结 8 1321
半阙折子戏
半阙折子戏 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 03:04

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

提交回复
热议问题