简体   繁体   English

递归函数错误1

[英]Recursive Function Error1

I am making a program that the user inputs integers and outputs them in reverse. 我正在制作一个程序,用户输入整数并反向输出它们。 It is a recursive function. 这是一个递归函数。 The Problem now is that it outputs an infinite of 0's. 现在的问题是它输出一个无限的0。 Please tell me where is the error in my code. 请告诉我代码中的错误在哪里。 and I need some pointers. 我需要一些指针。 Please help. 请帮忙。

#include <iostream>

using namespace std;

void printreverse(int);

int main()
{
    int x;
    cout << "Enter numbers: ";
    cin >> x;

    printreverse(x);

    return 0;
}
void printreverse(int x)
{
    if(x<10)
        cout << x;
    else
        cout << x%10;
        printreverse(x/10);
}

C++ is not Python. C ++不是Python。 You need to surround your else block by braces, like so 您需要用大括号将else块包围,就像这样

else
{ // need brace here
    cout << x%10;
    printreverse(x/10);
} // and here

otherwise only the first statement after the else is being executed (and the final printreverse(x/10) will always be executed, even for 0 , so you end up overflowing the stack). 否则,将仅执行else后面的第一个语句(并且始终会执行最终的printreverse(x/10) ,即使是0 ,也将导致堆栈溢出)。

I recommend you to always put braces, even for a single statement in an if/else , precisely for reasons similar to the one you just bumped into. 我建议您始终将括号括起来,即使对于if/else的单个语句,也正是出于与您刚碰到的类似的原因。

You have wrong identing in printreverse . 您在printreverse中printreverse错误。 It should be like this: 应该是这样的:

void printreverse(int x)
{
    if(x<10)
        cout << x;
    else
        cout << x%10;

    printreverse(x/10);
}

First it prints x or x%10, then it recurses regardless of what x is. 首先,它打印x或x%10,然后不管x是什么都重复递归。 If you wanted more than one statement done in a consequent or alternative you need to use a block. 如果要在结果或替代方案中完成多个语句,则需要使用一个块。 Blocks are denoted with {} in C-decendants. C分支中的块用{}表示。 They are so usual that some people actually think conditionals and control flow syntax need to have them. 它们是如此常见,以至于有些人实际上认为条件和控制流语法需要它们。 Anyway if the identing was the intended behaviour you should write it like: 无论如何,如果标识是预期的行为,则应将其编写为:

void printreverse(int x)
{
    if(x<10) {
        cout << x;
    } else {
        cout << x%10;
        printreverse(x/10);
    }
}

Whenever I use braces on one term in an if I add them for every one even when it's not really needed. 每当我在使用大括号上一个学期if我加入他们,即使不是真正需要它的每一个。 Some coding standards, like PSR2, require blocks always to remove the chance of ever getting bugs like this. 某些编码标准(例如PSR2)始终要求使用块,以消除出现此类错误的机会。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM