如果因子为零或1,则C++阶乘函数必须返回1 我在C++中写阶乘函数。我的功能运行良好。然而,在需求的基础上,函数必须计算并返回提供给它的数字的阶乘及其参数,如果 参数为正。如果它接收到的参数为负或零,则函数必须返回-1。 我似乎无法让它返回-1表示零或负数,如果它不返回负数表示正常的阶乘计算。这是到目前为止我的代码 #include <iostream> using namespace std; long factorial(int x) { if(x>1) return (x*factorial(x-1)); else return -1; } int main() { int number; cout << "Enter a number: " << endl; cin >> number; cout << factorial(number); cout << endl; return 0; }

如果因子为零或1,则C++阶乘函数必须返回1 我在C++中写阶乘函数。我的功能运行良好。然而,在需求的基础上,函数必须计算并返回提供给它的数字的阶乘及其参数,如果 参数为正。如果它接收到的参数为负或零,则函数必须返回-1。 我似乎无法让它返回-1表示零或负数,如果它不返回负数表示正常的阶乘计算。这是到目前为止我的代码 #include <iostream> using namespace std; long factorial(int x) { if(x>1) return (x*factorial(x-1)); else return -1; } int main() { int number; cout << "Enter a number: " << endl; cin >> number; cout << factorial(number); cout << endl; return 0; },c++,function,C++,Function,您需要两个基本案例: if (x <= 1) return -1 if (x == 2) return 2 else do the recursion 但这在数学上是不正确的。1和0的阶乘是1。您可以包装函数: long _factorial(int arg){ if(x>1) return (x*factorial(x-1)); else return 1; } inline long factorial(int arg){

您需要两个基本案例:

if (x <= 1) return -1
if (x == 2) return 2
else do the recursion

但这在数学上是不正确的。1和0的阶乘是1。

您可以包装函数:

long _factorial(int arg){
    if(x>1)
        return (x*factorial(x-1));  
    else 
        return 1;
}

inline long factorial(int arg){
    return (arg<=0)?-1:_factorial(arg);
}

所以我想我明白了。1的阶乘实际上需要是1,而不是-1。我的教授想要零和任何负数返回-1。谢谢大家的回复

#include <iostream>
using namespace std;

long factorial(int x)
{

if(x<=0)
    return -1;
if(x == 1)
    return 1;
if(x==2)
    return 2;   
else  
    return (x*factorial(x-1));

}

切换if/else语句顺序。首先检查0/1并返回-1,否则计算factorial12!是适合32位整数的最大阶乘。任何较大的值都会溢出,并且可能会给您带来负面结果。@jrok不是从34开始的0吗!?否则,我会期望大约一半的结果是否定的。如果我读对了标题,甚至1!结果应该是-1。注意,问题的文本与你的第一个版本一致。@Marglisse:好吧,我把它留给OP来整理。我的答案的重要部分是2个基本情况。所以我把实际问题弄糟了,1的阶乘应该读为1,而不是-1。此代码适用于所有其他代码。我试着把if语句改成ifx@JoshNicolet:你的第二个基本情况是什么?如果您的第一个基本情况是检查x,那么零的阶乘实际上等于1。第三个基本情况ifx==2是冗余的。在If with return之后的任何其他情况也是冗余的。