递归函数的return语句之前cout会停止它吗?

时间:2018-10-19 07:14:03

标签: c++ function recursion

在这里,如果我之前调用cout函数,则return语句不会被调用。

int factorial(int n){
 if(n>=2)
   cout<<"number of times the function called: "<<endl;
 return n*factorial(n-1);
       }

我希望它应该最后返回值 孔代码是

#include<iostream>
#include<stdio.h>
using namespace std;
int factorial(int n){
  if(n>=2)

  cout<<"number of times the loop executed: "<<n-1 <<endl;
   return n*factorial(n-1);

   }
  int main(){
  int number;
  cout<<"enter the number whose factorial is to be calculated..:"<<endl;
  cin>>number;
  int result=factorial(number);
  cout<<"factorial is: "<<result<<endl;
   }

2 个答案:

答案 0 :(得分:1)

if语句的主体可以是复合语句(由{}包围的语句列表),也可以是后接 single语句 if的状况。这意味着该代码:

if(n>=2)
    cout<<"number of times the function called: "<<endl;
    return n*factorial(n-1);

完全等同于:

if(n>=2){
    cout<<"number of times the function called: "<<endl;
}
return n*factorial(n-1);

您可能打算执行以下操作:

int factorial(int n){
    if(n>=2){
        cout<<"number of times the function called: "<<endl;
        return n*factorial(n-1);
    }
    return 1; // you should ALWAYS return something from a non-void function
}

答案 1 :(得分:0)

您必须使用以下方式终止递归:

return (n == 0 || n == 1) ? 1 : n*factorial(n-1);