c - 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!
解决方案
使用后缀减量运算符x--
时,表达式的值是应用减量之前的变量值。这意味着 x 的值仅rec
在所有子递归调用都已完成后的每次调用中实际递减。这就是为什么您7
在每一步都看到打印的原因 - 每个函数都执行递减并打印它,但传递8
给子函数。
但是,如果要为减量运算符添加前缀--x
,则该值将是应用赋值后变量的值。这将为您提供所需的结果,其中变量随着每次递归调用而递减。您也可以执行对 y 变量所做的操作,并指定x - 1
而不是x--
.
推荐阅读
- swiftui-navigationlink - NavigationLink 按钮可聚焦覆盖问题
- django - 无法将 django webapp 部署到谷歌云上
- kotlin - 使用 JpaRepository 模拟抛出 ClassCastException
- javascript - 向数组 mongoDB 中的对象添加字段
- c# - 服务总线本地开发
- php - 我可以在电话上做什么?
- python - Python - 如何使用 pdfrw 正确填充 PDF 表单中的多行文本字段?
- python - 实现用于实时说话人识别的 Python 多处理模块
- java - OAuth 同意屏幕没有突然显示,没有错误?
- algorithm - 用于两种不同场景的插入、删除、包含和覆盖间隔的数据结构