【问题标题】:What can I do in this code to prompt an error when a negative number is used?当使用负数时,我可以在这段代码中做些什么来提示错误?
【发布时间】:2019-04-22 09:38:18
【问题描述】:

我想知道当我输入负数时如何提示错误。我为这个程序使用了一个 for 循环。这个程序所做的,或者至少它应该做的,是输出任何给定数字的因子(如果是正数)。但是我不确定如何让我的代码提示错误,或者如果输入的数字小于或等于 0,至少会继续询问一个数字。

我使用变量n作为用户输入的数字。

我对编程真的很陌生,我渴望尽快完成这个程序。你能帮忙吗?

  #include <iostream>
  #include <math.h>
  #include <stdlib.h>
  using namespace std;


int main()
{
double n;
cout << "Welcome to this program... Hope you like it" << flush << endl;
do
{
    int i, fact = 1, n;
    cout << "Please enter a value for the variable " "n: ";
    cin >> n;

    for (i = 1; i <= n; i++) {
        fact = fact * i;
    }
    cout << "Factorial of " << n << " is: " << fact << endl;
    cout << " Thanks for using this program... hope you liked it!" << endl;
} while (n >= 0);
return 0;
}

【问题讨论】:

  • 等等。您有 2 个ns。最好不要这样做。这是合法的,因为它们在不同的范围内,但它是混乱的根源。
  • 考虑绘制一张您希望代码执行的操作的图片。然后画出代码的作用。他们移动代码,直到代码所做的图片与代码应该做的相匹配。

标签: c++ visual-studio-2010 visual-c++


【解决方案1】:

代码中的注释:

#include <iostream>

// it's best not to do using namespace std. It's a huge namespace

int main()
{
    std::cout << "Welcome to this program... Hope you like it\n";
    do
    {
        int i, fact = 1, n;
        std::cout << "Please enter a value for the variable " "n: ";
        std::cin >> n;

        // if std::cin is in a failed state then break out of the loop.
        if (std::cin.fail()) break;

        // added check if n<0. if n<0 ptint error on stderr
        if (n<0) {
            std::clog << "Error: you must supply a number equal to or greater than zero\n";
        } else { // if n>=0 
            for (i = 1; i <= n; i++) {
                fact = fact * i;
            }
            std::cout << "Factorial of " << n << " is: " << fact << "\n";
        }
    } while (true); // <- now always true 

    std::cout << "\nThanks for using this program... hope you liked it!\n";
    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-30
    • 1970-01-01
    • 2013-01-18
    • 1970-01-01
    • 2020-11-08
    • 2022-12-05
    相关资源
    最近更新 更多