【问题标题】:Trying to keep the function going till a valid number is entered尝试保持函数运行直到输入有效数字
【发布时间】:2019-10-21 16:30:20
【问题描述】:

我正在尝试编写一个程序来计算给定数字的阶乘。但是如果用户输入一个小于或等于 0 的数字,我希望程序一直想要它,直到他输入一个大于 0 的数字。

#include <iostream>
using namespace std;
void facto(int a){
    int faktoriyel = 1;
    for(int i=1;i<=a;i++){
        faktoriyel *=i;
}
    cout << "The result:" << faktoriyel << endl;
}
int main(){
    int a;
    cout<<"Please enter a valid number:"; cin >> a;
    if(a<=0){
        cout<<"You entered an invalid number. Please try again.";
}
    while(a<=0);
    facto(a);
    return 0;

}

当我输入无效数字时,程序要求我重试,但我无法输入任何数字。所以我的问题是:

a)我该怎么做?

b)我的代码中有什么不清楚的地方吗?

c)如果我希望程序在我按下输入按钮之前给我输入的数字的结果怎么办?我该怎么做? (比如,我希望它按照 6 24 120 的顺序给我 3 4 和 5 的结果,然后按 Enter 键结束程序)

【问题讨论】:

  • while(a&lt;=0); 不是您编写实际 while 循环的方式(这个循环要么是无限的,要么永远不会执行)

标签: c++ while-loop factorial


【解决方案1】:

这不起作用:

while(a<=0);

;while 循环的函数体。就其本身而言,它什么也不做,也不会影响前面的if 循环。所以基本上,结果是一个无限循环,如果a &lt;= 0 永远不会做任何事情。相反,试试这个:

int a;
cout<<"Please enter a valid number:"; cin >> a;
while(a<=0){
    cout<<"You entered an invalid number. Please try again.";
    cin >> a;
}

现在这两个语句在 while 的正文中,它应该可以按预期工作。

关于 c),这需要一些修改,因为默认情况下 cin 不会因为您按下回车键而停止阅读。你可以这样做:

#include <iostream>
#include <string>
#include <sstream>
using namespace std;
void facto(int a){
    int faktoriyel = 1;
    for(int i=1;i<=a;i++){
        faktoriyel *=i;
    }
    cout << "The result:" << faktoriyel << endl;
}

int main() {
    cout << "Please enter a valid number:" << endl;
    std::string line;
    std::getline(cin, line);
    std::stringstream stream(line);
    int a;
    while (1) {
        stream >> a;
        if (!stream) {
            break;
        }
        if (a <= 0) {
            cout << "You entered an invalid number. Please try again." << endl;
        }
        else facto(a);
    }
}

【讨论】:

  • 没问题,很高兴它有帮助。
  • 完美运行!但是由于我对 C++ 编程很陌生,所以在“std::string line;”之后我无法理解它是如何工作的。 getline 和 stringstream 是如何工作的?什么是流(线)?上帝,我的问题带来了更多的问题......
  • std::getline(cin, line); 告诉它只获取一行,否则cin 不会因为您按下回车键而停止。所以现在line 是一个std::string 持有输入的数字。我们希望它的行为类似于cin(这是一个std::istream),所以我们使用stream(line) 来创建一个带有行内容的std::stringstream。现在可以在while 循环中使用它来将数字流式传输到a,就像我们之前为此目的使用cin 一样。
  • 谢谢!我会进一步研究它,看看它是如何工作的。
【解决方案2】:

您可以使用一段时间来验证您的号码的有效性:

while (a<=0){
    cout<<"You entered an invalid number. Please try again.";
    cin >> a;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-05
    • 1970-01-01
    • 2021-01-24
    • 1970-01-01
    相关资源
    最近更新 更多