#include <iostream>
using namespace std;
int raisetoPower(double x, int power){
double result;
int i;
result = 1.0;
if(i == 0){
result = 1;
}
else if(i > 0){
for(int i = 0; i < power; i++){
result *= x;
}
}
else{
for(int i =0; i > power; i--){
result *= x;
}
result = 1/result;
}
return result;
}
int main(){
double x;
int i;
cout << "Enter the number: ";
cin >> x;
cout << "Enter the power to which you wanna raise the number: ";
cin >> i;
cout << x << " raise to the power " << i << " is equal to " << raisetoPower(x, i);
}
I’ve written this code to make a function that could be used like a modulus operator as of JavaScript. Everything in this code is working fine except the block of code encapsulated in else statement. As it is written to handle negative powers but it is always returning 0 as answer. I tried to solve it but all in vain.
New contributor
Mark is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.