首页 > 解决方案 > Recursion order of outputs in C

问题描述

I have this recursive function in C,and i'm trying to understand why it's printing the way it does:

void rec(int x, int y){
 if (x == y) 
     return;
 rec(x--, y+1);
 printf("%3d%6.2f\n", x, (float) y);
}

I know that ther output for rec(8,4) is:

7 7.00
7 6.00
7 5.00
7 4.00

why the X value stays 7?as i understand it, the x-- should happen only after the line it's written.If not,why the value stays 7 and not decreasing? Also why the y value is decreasing?because it starts printing when the recursion is stopped?

I'm pretty new to C,and not used to all the little details that require attention(i'm coming from java)

thanks for any help!

标签: crecursion

解决方案


使用后缀减量运算符x--时,表达式的值是应用减量之前的变量值。这意味着 x 的值仅rec在所有子递归调用都已完成后的每次调用中实际递减。这就是为什么您7在每一步都看到打印的原因 - 每个函数都执行递减并打印它,但传递8给子函数。

但是,如果要为减量运算符添加前缀--x,则该值将是应用赋值变量的值。这将为您提供所需的结果,其中变量随着每次递归调用而递减。您也可以执行对 y 变量所做的操作,并指定x - 1而不是x--.


推荐阅读