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

时间:2019-10-25 06:17:33

标签: c++ function median

输入验证:

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

因此,我已经完成了作业,唯一缺少的是如上所述的输入验证。换句话说(根据我的轻描淡写),我应该在代码中实现一个循环,如果用户之前输入负数,则用户必须输入另外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;
}

如果用户输入一个负数,我希望输出为“输入3个整数” //因为我们只需要正数

3 个答案:

答案 0 :(得分:1)

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

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

否则,只有一会儿循环:

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

希望这会有所帮助,谢谢 -拉杰库玛(Rajkumar)

答案 1 :(得分:0)

event

使用以下命令打印数字后,不要忘记等待用户的按键操作:

SELECT A.id, A.name, B.lg, B.event FROM Table_A A LEFT JOIN (SELECT enrolid, MAX(lg) AS max_lg FROM Table_B GROUP BY enrolid) M ON M.enrolid = A.id LEFT JOIN Table_B B ON B.enrolid = M.enrolid AND B.lg = M.max_lg ORDER BY A.id

id name lg event 1 John 70 G 2 Mike 60 D 3 Dave 60 F 4 Sarah null null

答案 2 :(得分:-1)

您可以使用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;
    }
}