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

时间:2018-06-04 09:45:01

标签: c++ loops recursion while-loop codeblocks

我正在做一个递归来找到一个数字的阶乘,当我写这个函数时一切都很顺利:

#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;
}

}

但是我想添加一个关于if是否为0或者&lt; = -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;}
}

}

1 个答案:

答案 0 :(得分:1)

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

你需要写下这个:

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

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