首页 > 解决方案 > 即使没有满足条件,我也无法通过几个 do-while 循环

问题描述

我只是在做一个练习,我应该找到两个特定整数之间的所有偶数。但是,每次我输入任何数字时,我都会在前两个 do-while 循环中的一个中遇到问题。我假设我犯了一个简单的错误。有人看到我做错了吗?谢谢!

输入应该是 x 和 y,输出应该是 b。x 必须小于 y,并且它们都必须在 1-99 之间(我会解决这个问题,它应该是 0-100。)

#include <iostream>

int main()
{
    int x, y, b;

    std::cout << "This program will show all even numbers between a certain range.\n\nEnter two integers >0 and <100. The first integer must be smaller than the second integer.\n ";
    std::cin >> x >> y;

    do
    {
        std::cout << "The first integer must be smaller than the second integer. Please enter two integers.\n ";
        std::cin >> x >> y;

    } while (x > y);

    do
    {
        std::cout << "The first smaller integer must be greater than 0, the second larger integer must be less than 100.\n ";
        std::cin >> x >> y;

    } while (((x < 0 || y > 100 || x > y)));

    b = x;

    if ((b % 2) == 0)
    {
        do
        {
            std::cout << b;
            b++;
        } while (b < y);
    }
}

标签: c++do-while

解决方案


这是一个相当典型的“循环半”情况。

也就是说,你需要提示用户输入,阅读输入,然后如果输入错误,告诉他们它是错误的,然后重复。

老实说,大多数处理这种情况的方法最终都至少有点笨拙。也就是说,避免大多数笨拙的一种可能性是这样的:

bool CheckInput(int a, int b) { 
     if (b < a) {
         std::cout << "The first item must be less than the second.\n");
         return false;
     }

     // add range checks here....

     return true;
}

int main() {
    int x, y;

    do { 
        std::cout << "Please enter two integers (in sorted order): ";
        std::cin >> x >> y;
    } while (!CheckInput(x, y));
}

推荐阅读