带有值的递归阶乘错误return语句,函数返回' void' [-fpermissive]

时间:2015-01-27 18:09:48

标签: c++ recursion

我尝试使用递归函数编写一个阶乘。这段代码有什么问题? 我得到一个带有值的错误return-statement,函数返回' void' [-fpermissive]

#include <iostream.h>

int factorial(int);

int factorial(int number)
{
    return number==0?1: number * factorial*(number - 1);
}

void main(void)
{
    int number;

    cout << "Please enter a natural number: ";
    cin >> number;
    if (number < 1)
        cout << "That is not a natural number.\n";
    else
        cout << number << " factorial is: " << factorial(number) << endl;
    return 0;
}

2 个答案:

答案 0 :(得分:1)

函数main应该返回int,而不是void。括号内的void在C ++中也是无用的。

使用:

int main() {

或:

auto main() -> int {

答案 1 :(得分:0)

修复代码。 main必须是int,并且函数参数应该立即输入而不需要*

#include <iostream.h>

int factorial(int number)
{
    return number==0?1: number * factorial(number - 1);
}

int main(void)
{
    int number;

    cout << "Please enter a natural number: ";
    cin >> number;
    if (number < 1)
        cout << "That is not a natural number.\n";
    else
        cout << number << " factorial is: " << factorial(number) << endl;
    return 0;
}