【问题标题】:C++ Recursion how to use if statement in whileC++递归如何在while中使用if语句
【发布时间】:2018-11-13 14:49:41
【问题描述】:

我正在递归查找数字的阶乘,当我编写函数时一切正常:

#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 x is = 0 或

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

}

【问题讨论】:

  • 如果用户输入的值 = 0 或 ,我想显示“请输入正确的值以找到阶乘”
  • x=0 哦,不......代替比较的分配应该是==。此外,0 的阶乘是 1。

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


【解决方案1】:

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

你需要这样写:

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

正如 Karsten Koop 指出的那样,您最好将其写为 if(x&lt;=0)

【讨论】:

  • x 是一个int,所以可以简化为x&lt;=0
  • @gamesymbol Btw 0 有一个有效的阶乘。
猜你喜欢
  • 2014-12-15
  • 1970-01-01
  • 2015-07-06
  • 2016-02-29
  • 2019-04-08
  • 1970-01-01
  • 2017-12-05
  • 2012-11-28
  • 2020-11-03
相关资源
最近更新 更多