我编写了一个程序,通过递归计算给定nuber的阶乘,并另外显示递归调用的数量。
当我将结果存储在分离的变量“result”
时,它按预期工作long long result = calculateFactorial(factorialNumber, counter);
cout << "\nfactorial is equal to: " << result
<< "\nRecursion executed: " << counter - 1 << " times.\n";
但是当我想这样做的时候:
cout << "\nfactorial is equal to: " << calculateFactorial(factorialNumber, counter)
<< "\nRecursion executed: " << counter - 1 << " times.\n";
计数器始终等于初始值-1(-1)。你能解释一下,为什么第二种方法不能正常工作?
代码:
#include <iostream>
using namespace std;
long long calculateFactorial(int factorialNumber, int &counter);
int main() {
int counter = 0;
int factorialNumber;
cout << "Enter factorial number: ";
cin >> factorialNumber;
long long result = calculateFactorial(factorialNumber, counter);
cout << "\nfactorial is equal to: " << result
<< "\nRecursion executed: " << counter - 1 << " times.\n";
//counter - 1, because first execution is nor recursion.
}
long long calculateFactorial(int factorialNumber, int &counter) {
if (factorialNumber == 0) {
return 1;
}
if (factorialNumber > 0) {
counter++;
return factorialNumber * calculateFactorial(factorialNumber - 1, counter);
}
return 2;
//error code - can be captured
}
谢谢:)