Why is my power operator (^) not working?

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

    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;
    }
    
    0 讨论(0)
  • 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 <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;
    }
         
    
    0 讨论(0)
提交回复
热议问题