Using Recursion to raise a base to its exponent - C++

后端 未结 5 687
不知归路
不知归路 2020-12-22 10:42

I simply want to write some code that makes use of recursion of functions to raise a base to its power. I know that recursion is not the most right way to do things in C++,

5条回答
  •  北荒
    北荒 (楼主)
    2020-12-22 11:15

    int raisingTo(int base, unsigned int exponent)
    {
        if (exponent == 0)
            return 1;
        else
            return base * raisingTo(base, exponent - 1);
    }
    

    You have 3 main problems:

    • You don't have to use pow function
    • To compare number you should use == as = is an assignment not compare.
    • You missed that if exponent is equal 0 you should return 1.

提交回复
热议问题