C ++递归如何在while中使用if语句

C++ Recursion how to use if statement in while

我正在做一个递归来求一个数的阶乘,当我写这个函数时一切顺利:

#include <iostream>

using namespace std;

int factorialfinder(int x){
if(x==1){
    return 1;
}else{
    return x * factorialfinder(x-1);
}
}

int main()
{
int x;
cout << "Please enter a number for the factorial finder " << endl;
cin >> x;
cout << "The factorial of " << x << " is " << factorialfinder(x) << endl << endl;
cout << "Enter another number for the factorial finder " << endl;


while(x > -1){
    cin >> x;
    cout << "The factorial of " << x << " is " << factorialfinder(x) << endl << endl;
    cout << "Enter another number for the factorial finder " << endl;
}

}

但我想添加一个关于如果 x 是 = 0 或 <= -1 的 if 语句,那么它会显示一条错误消息,但我不能在 while 循环中使用它是否会导致错误并自动执行此操作为什么要终止我的程序? :

#include <iostream>

using namespace std;

int factorialfinder(int x){
if(x==1){
    return 1;
}else{
    return x * factorialfinder(x-1);
}
}

int main()
{
int x;
cout << "Please enter a number for the factorial finder " << endl;
cin >> x;
cout << "The factorial of " << x << " is " << factorialfinder(x) << endl << endl;
cout << "Enter another number for the factorial finder " << endl;


while(x > -1){
    cin >> x;
    if(x = 0 || x <= -1){
    cout << "Please enter a proper value to find the factorial";}
    else{
    cout << "The factorial of " << x << " is " << factorialfinder(x) << endl << endl;
    cout << "Enter another number for the factorial finder " << endl;}
}

}

你的 if 语句是错误的,你使用的是赋值运算符 = 而不是比较 ==

你需要这样写:

 if(x == 0 || x <= -1)

你最好把它写成 if(x<=0) 正如 Karsten Koop 指出的那样