返回factorial C ++

时间:2018-05-06 16:51:52

标签: c++ function recursion factorial

我试图通过C ++ Primer Plus书中的以下练习解决。

  

定义一个递归函数,该函数接受一个整数参数并返回   这个论点的阶乘。回想一下3阶乘,写3!   等于3×2!等等,0!定义为1.一般来说,如果n是   大于零,n! = n *(n - 1)!在程序中测试您的功能   使用循环允许用户输入其中的各种值   该计划报告了阶乘。

我编写了进入main()的代码。

#include <iostream>
using namespace std;

int factorial(int n);


int main()
{
    int number= 0;
    cout<<"Enter a number(0 to quit): ";
    while (cin >> number && number! = 0)
    {
        cout<< "Here is the factorial of the number: "<< factorial (number) << ". \n"
        "Enter next number(0 to quit): ";
    }


    return 0;
}

现在我想不出一个正确的递归函数声明。有人可以通过编写最简单的(编程新手)来掌握本练习的函数声明吗?

3 个答案:

答案 0 :(得分:1)

在设计递归算法来计算任何数的阶乘时,我们必须首先确定基本情况,这是我们可以在没有递归的情况下解决的计算的一部分。那就是sql = "SELECT `xyz` FROM `checkins` WHERE `name`=%s AND `timestamp` >=%s AND `timestamp` < %s ORDER BY `%s` DESC LIMIT 1" query.execute(sql, (name, start, end, field)) 然后n = 0

的情况

这说明当factorial(n) = 1等于0时如何解决问题,但当n大于0时我们该怎么做?这是递归情况,或者我们使用递归来解决的问题的一部分。 n。这表明如果n大于0,则n的阶乘是If n > 0, then factorial(n) = n * factorial(n-1)的阶乘的n倍。

n-1

答案 1 :(得分:0)

我会按照以下方式做点什么:

int factorial(int n){
  if(n<=0)
    return 1;
  int num=factorial(n-1);
  if(num)
    return n*num;
  return 0;
}

答案 2 :(得分:0)

您可以按如下所示使用非常简短的函数,但它与@superPhreshHackerKid提供的答案相同

onSubmit(){    
 /*
  *  FlatList is a PureComponent which means that it will not re-render              
  *  if props remain shallow-equal So, We are Cloning the items array to           
  *  clonedArray, So that the reference to this.state.items  will change.
  *  Means this.state.items === clonedArray will give false value.
  */
   let clonedArray = this.state.items.slice();
   clonedArray.push({key:this.state.userdata});
   this.setState({items: clonedArray});
}

希望有帮助

相关问题