如果输入数字为负数如何循环

How to loop if input number is negative

输入验证:

如果数字为负,程序应输出错误并让用户重试。只需要一次迭代(即你的程序不需要提示另外三个数字,它可以在打印结果后退出)。

所以我已经完成了作业,我唯一缺少的就是如上所述的输入验证。换句话说(根据我的轻描淡写),我应该在我的代码中实现一个循环,如果用户之前输入了负数,则用户必须输入另外 3 组数字。

#include <iostream>
#include <iomanip>
using namespace std;

double getAverage (double num1, double num2, double num3){

    double averageAmount;

    averageAmount = (num1 + num2 + num3)/ 3;

    return averageAmount;
}
double getMedian (int num1, int num2, int num3){

       int x = num1-num2;
       int y = num2-num3;
       int z = num1-num3;
       if(x*y > 0) return num2;
       if(x*z > 0) return num3;
       return num1;
}
double countDigits( int num1){

    int digits = 0;

    while (num1){

        num1 = num1/10;
        digits++;
    }

    return (digits);
}

int main() {

    double num1 = 0;
    double num2 = 0;
    double num3 = 0;

    cout << "Enter 3 integers" << endl;
    cin >> num1;
    cin >> num2;
    cin >> num3;

    cout << "The average is " << fixed << setprecision(2) << getAverage(num1, num2, num3) << endl;
    cout << "The median is " << fixed << setprecision(2) << getMedian(num1, num2, num3) << endl;
    cout << "There are " << countDigits(num1) << " digits in the number " << num1 << endl;

    return 0;
}

如果用户输入负数,我希望输出为 "Enter 3 integers" // 因为我们只需要正数

您可以使用for循环来输入数字。

当用户输入任何负数时,您可以显示错误消息并退出主函数。

例如:

double num[3];

cout << "Enter 3 positive integers" << endl;
for(int i=0; i<3; i++) {
    cin >> num[i];
    if (num[i] < 0 ) {
        cout << "Only 3 positive integers are allowed";
        return 0;
    }
}

您可以使用 do-while 循环编写代码:

do {
   cout << "Enter 3 integers" << endl;
   cin >> num1;
   cin >> num2;
   cin >> num3;
} while ((num1 < 0) || (num2 < 0) || (num3 < 0));

否则只有一个 while 循环:

while (true) {
   cout << "Enter 3 integers" << endl;
   cin >> num1;
   // if any number is -ve, continue the whole loop
   if (num1 < 0) continue;
   cin >> num2;
   if (num2 < 0) continue;
   cin >> num3;
   if (num3 < 0) continue;
   // if every number is positive, just break out of the loop
   break; 
}

希望对您有所帮助,谢谢 - 拉杰库马尔

cout << "Enter 3 integers" << endl;
        cin >> num1;
        cin >> num2;
        cin >> num3;

            while(num1 < 0 || num2 < 0 || num3 < 0)
            {
                if (num1 < 0)
                {
                    cout << "Your first number [" << num1 << "] is negetiv. Please enter a positive number!";
                    cin >> num1;
                }
                if (num2 < 0)
                {
                    cout << "Your second number [" << num2 << "] is negetiv. Please enter a positive number!";
                    cin >> num2;
                }
               if (num3 < 0)
                {
                    cout << "Your third number [" << num3 << "] is negetiv. Please enter apositive number!";
                    cin >> num3;
                }
            }

使用以下方法打印数字后不要忘记等待用户按键:

cin;

system("pause");