Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compute 5 to the power of 3, but it returns 0. Why?

Tags:

c++

function

#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), 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!

like image 470
John Avatar asked Dec 09 '22 08:12

John


1 Answers

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.]

like image 136
Oliver Charlesworth Avatar answered Dec 25 '22 22:12

Oliver Charlesworth