#include
void main(void)
{
int a;
int result;
int sum = 0;
printf(\"Enter a number: \");
scanf(\"%d\", &a);
for( int i =
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 int
s:
int power(int base, int exp)
{
int result = 1;
while(exp) { result *= base; exp--; }
return result;
}
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;
}