跟踪输出,即使在调试时也无法弄清楚?
Tracing the output, could not figure it out even when debugging it?
调用函数f4时函数returning 6如何?我真的搞不懂这个函数是如何运作的,不应该只是 return 1 吗?因为 (n-1)
#include <iostream>
#include<cmath>
#include<fstream>
using namespace std;
int x = 3;
void f1(int, int &);
int f4(int);
int main()
{
int x = 5; int y = 10;
f1(x, y);
cout << x << "\t" << y << endl;
x = 15; y = 20;
f1(x++, x);
cout << x << "\t" << y << endl;
x = 3;
cout << f4(x) << endl;
system("pause");
return 0;
}
void f1(int a, int &b)
{
a *= 2; b += x;
cout << a << "\t" << b << endl;
}
int f4(int n) {
if (n == 1 || n == 0)
return n;
else
return n + f4(n - 1);
}
f4
函数是递归的。使用 1 或 0 以外的数字调用将使它递归。你用 3 调用它,所以编译器(简化)看到
f4(3) => 3 + f4(2) => 3 + 2 + f4(1) => 3 + 2 + 1 => 5 + 1 => 6
递归简述..
int f4(int n) {
if (n == 1 || n == 0)
return n;
else
return n + f4(n - 1);
}
您的代码指出,当 n 为 1 或 0 时,只需 return n,否则将 n 添加到函数的结果中。
这会设置一个递归堆栈,其中第一个调用 n = 3 并递归。
在下一次调用 n = 2 时递归。
在下一次调用 n = 1 时,它 returns 以及堆栈的其余部分导致 1 + 2 + 3 即 6。
调用函数f4时函数returning 6如何?我真的搞不懂这个函数是如何运作的,不应该只是 return 1 吗?因为 (n-1)
#include <iostream>
#include<cmath>
#include<fstream>
using namespace std;
int x = 3;
void f1(int, int &);
int f4(int);
int main()
{
int x = 5; int y = 10;
f1(x, y);
cout << x << "\t" << y << endl;
x = 15; y = 20;
f1(x++, x);
cout << x << "\t" << y << endl;
x = 3;
cout << f4(x) << endl;
system("pause");
return 0;
}
void f1(int a, int &b)
{
a *= 2; b += x;
cout << a << "\t" << b << endl;
}
int f4(int n) {
if (n == 1 || n == 0)
return n;
else
return n + f4(n - 1);
}
f4
函数是递归的。使用 1 或 0 以外的数字调用将使它递归。你用 3 调用它,所以编译器(简化)看到
f4(3) => 3 + f4(2) => 3 + 2 + f4(1) => 3 + 2 + 1 => 5 + 1 => 6
递归简述..
int f4(int n) {
if (n == 1 || n == 0)
return n;
else
return n + f4(n - 1);
}
您的代码指出,当 n 为 1 或 0 时,只需 return n,否则将 n 添加到函数的结果中。
这会设置一个递归堆栈,其中第一个调用 n = 3 并递归。 在下一次调用 n = 2 时递归。 在下一次调用 n = 1 时,它 returns 以及堆栈的其余部分导致 1 + 2 + 3 即 6。