c++ - 递归的权力

标签 c++ recursion

<分区>

我正在尝试制作一个程序,它接受输入 x,然后将其置于 (x-1) 的幂并将其添加到 (x-1)^(x-2) 等。使用递归。

例如:x = 3:3^2 + 2^1 + 1^0 = 12

这是我的:

#include <stdio.h>
#include <iostream>
#include <cmath>

using namespace std;

int foo(int x) {

    if (x = 0){
        return 0;
    }

    if (x > 0){
        return (pow(x, (x - 1)) + foo(x - 1));
    }
}

int main(){
    int result = foo(3);
    cout << result << endl;
    return 0;

我只是想知道问题是什么,因为我一直在试图弄清楚为什么我一直得到输出 -858993460

最佳答案

您的代码有多个问题... 首先....

if (x = 0){
        return 0;
    }

if block 将永远不会执行,因为 x 将始终分配给 0,这会导致 false。将其更改为

if (x == 0){
        return 0;
    }

其次,有一个返回未定义行为的代码路径,因为第一个 if block 在分配给 0 后从未执行。

int foo(int x) {

    if (x = 0){
        return 0;
    }

    if (x > 0){
        return (pow(x, (x - 1)) + foo(x - 1));
    }

    //WHERE is your default return???
}

这是一个修复后的版本...

int foo(int x) {

    if (x < 1)
        return 0;
    return (pow(x, (x - 1)) + foo(x - 1));
}

顺便说一句,当x == 3时,答案是12; ---> 3^2 + 2^1 + 1^0 = 12

关于c++ - 递归的权力,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36926872/

相关文章:

javascript - 无法识别触发 "maximum call stack size exceeded"错误的递归

c++ - Dijkstra 算法 : memory consumption

java - 使用递归在二维数组中查找 4 个连续的 1

algorithm - Clog n的一个算法问题的设计[C++代码]

c - 在 linux 中实现 ls -R 命令

java - 在 BST 中查找比给定值更高的值的数量

c++ - 添加 noexcept 会破坏二进制兼容性吗?

c++ - CMakeLists.txt :30 (project): No CMAKE_C_COMPILER could be found 处的 CMake 错误

C++ : Cookie not stored in one machine, 但存储在另一个

c++ - Valgrind 输出和 rdtsc 不一致......为什么会这样?