Reputation: 5
This program is supposed to take two numbers (a base and an exponent) and calculate the power. For example, base 5 to the power of 2 should equal 25. But when I input these two numbers, it won't output the result. Here is my code:
#include <iostream>
#include <cmath>
using std::cout;
using std::cin;
using std::endl;
double power(double base, int exponent) //declaring and defining
{
double result = 1;
for(int i = 0; i = exponent; i++) // @suppress("Assignment in condition")
{
result = result + base;
}
return result;
}
void print_pow(double base, int exponent)
{
double myPower = power(base, exponent);
cout << base << " raised to the " << exponent << " power is " << myPower << endl;
}
int main()
{
double base;
int exponent;
cout << "What is the base? ";
cin >> base;
cout << "What is the exponent? ";
cin >> exponent;
print_pow(base, exponent);
}
Console:
What is the base? 5`
What is the exponent? 2
After entering these two numbers, it is missing the answer. It is just a blank line on my console.
Upvotes: 0
Views: 127
Reputation: 70
the power function should be `
double power(int base, int exponent)
{
double result = 1;
for(int i = 0; i < exponent; i++)
{
result *= base;
}
double result;
}`
Upvotes: -2
Reputation: 440
The problem with your code is already stated in comment by @Yaroslav Fyodorov but the solution could be as simple as using standard function:
double myPower = std::pow(base, exponent);
Your power() implementation is not necessary at all.
Upvotes: 1
Reputation: 2018
You should probably change:
for(int i = 0; i = exponent; i++)// @suppress("Assignment in condition")
To:
for(int i = 0; i < exponent; i++)
And also the calculation line in the loop should feature multiplication:
result = result * base;
Why do you import cmath and then calculate power in a loop (very inefficient way)?
Upvotes: 1
Reputation: 1155
Your power()
function has two issues. First of all, the condition in the for loop is wrong (it's i = exponent
, which is an assignment, when it should be i < exponent
). Secondly, the expression should be result = result * base
to get the desired result.
double power(double base, int exponent) //declaring and defining
{
double result = 1;
for(int i = 0; i < exponent; i++)
{
result = result * base;
}
return result;
}
Upvotes: 3