# 孟婆汤## 题目描述孟婆想尝尝孟婆汤什么味但是又担心自己喝了之后什么都不记得了于是写了一张纸条贴在醒目的地方:我想尝尝这汤什么味。咕噜咕噜……孟婆:我是谁?我在哪?我要干什么?抬头一看:我要尝尝这汤什么味。好咧!咕噜咕噜…………从我们的角度看来她属于是无限递归。现在想请你计算下面这个程序递归 n 层之后 sum 等于多少?sum 是全局变量C++版C++void dfsint cnt c
#include <iostream>
using namespace std;
int sum = 0;
void dfs(int cnt) { // cnt 从 1 开始 如同 dfs(1)
for(int i = 1; i <= cnt; i++) {
sum++;
}
if(cnt + 2 <= 1000) { // 注意需要判断 cnt + 2 是否超过 n 的范围
dfs(cnt + 2);
}
}
int main() {
int n;
cin >> n;
dfs(1);
cout << sum << endl;
return 0;
}
原文地址: https://www.cveoy.top/t/topic/fbmE 著作权归作者所有。请勿转载和采集!