Compute 5 to the power of 3, but it returns 0. Why?
#include <iostream>
double power (double z, int n)
{
double result(0.0);
for (int i = 1; i <= n; i++)
result *= z;
return result;
}
int main()
{
int index(3);
double x(5.0), 开发者_JS百科double y(0.0);
y = power (x, index);
std::cout << y << std::endl;
return 0;
}
Hello, where is the mistake in this code, please?
Thanks!
Because result
is initialised to 0
. And as we know, 0 * anything == 0
. You need to start at 1
.
[In future, please learn how to debug! You would easily have spotted this if you had stepped through your code in a debugger, or added some printf
statements to your function.]
Mistake is double result(0.0);
. 0 multiplied by anything is 0.
Must be double result(1.0);
In your power function, your result
is initialized to be 0.0, then when you multiply it by z n times, you just multiply 0 by z.
You should change double result(1.0);
.
Your result should be initialized to 1.0 not to 0.0.
精彩评论