c - 为什么 C 中的递归会向后打印?

标签 c visual-studio-2012 recursion

我认为这个程序的输出将是4321。即模1234 = 4,然后除以10得到123,所以模123 = 3......完成后应该是4321。但输出是1234。有人可以解释一下这是怎么发生的吗?非常感谢,节日快乐。

void printnumber(int n) { //function declaration
    if (n < 0) {
        putchar('-');
        printnumber(-n); //recursive call
    } else {
        if (n >= 10) {
            printnumber(n / 10); //second recursive call
        }
        putchar('0' + (n % 10));
    }
}
int main() {
    int n = 1234;
    printnumber(n);
    putchar('\n');
    return 0;
}

最佳答案

First call to function, input 1234

   Second call to fucntion, input 123

      Third call to function, input 12

          Fourth call to function, input 1

          print 1 and return

      print 2 and return

   print 3 and return

print 4 and return

Output: 1234

关于c - 为什么 C 中的递归会向后打印?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27662595/

相关文章:

c - 使用微软编译器减少 opencl 内置 vector 类型的功能?

c# - 如何让 VS 假定所有内容默认都是公开的

javascript - 分形树递归问题

c - 为什么两个元素从字符串(从 char 到 int)的转换不能相加?

阻止 recv() 返回少于请求字节的情况

将 float 从 0 转换为 1 到 RGB 16bit

visual-studio-2012 - 在 Visual Studio 11 Beta 的文件范围内快速查找/查找

c# - Visual Studio 找不到符号,虽然类在目录中,但它没有出现在解决方案资源管理器中

python - 哪个代码删除了排列中的重复组合

objective-c - 递归 block 保留循环