为什么我的“其他如果”声明不起作用?

时间:2017-02-22 02:19:33

标签: c++ if-statement factorial

由于某种原因,我的else if声明无效。当我使用输入“20”运行代码时,当我的else if语句应该为此纠正时,我得到因子的表达式然后为“20”。

#include <iostream>

unsigned int factorial(unsigned int number);

int main()
{
    unsigned int number;
    std::cout << "Please enter a positive interger. ";
    std::cin >> number;
    std::cout << "facorial of " << number << " = " << factorial(number);
    return 0;
}

unsigned int factorial(unsigned int number)
{
    if (number > 1 && number < 20) {
        return number * factorial(number - 1);
    }
    else if (number >= 20) {
        std::cout << "error" << std::endl;
    }
    else
        return 1;
}

1 个答案:

答案 0 :(得分:2)

如果您的阶乘函数导致未定义的返回,则您不会退出其他人: What if I don't put a return value to a function whose prototype returns a value

您获得的数字不是该函数的结果,而是未定义的值。

#include <iostream>

unsigned int factorial(unsigned int number);

int main()
{
    unsigned int number;
    std::cout<< "Please enter a positive interger. ";
    std::cin >> number;
    std::cout << "facorial of " << number << " = " << factorial(number);
    return 0;
}

unsigned int factorial(unsigned int number)
{
    if (number > 1 && number < 20){
        return number * factorial(number - 1);
        }
    else if (number >= 20){
        std::cout << "error" << std::endl;
        return 0;
        }
    else
        return 1;
}