c++ - 即使没有满足条件,我也无法通过几个 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);
}
}
解决方案
这是一个相当典型的“循环半”情况。
也就是说,你需要提示用户输入,阅读输入,然后如果输入错误,告诉他们它是错误的,然后重复。
老实说,大多数处理这种情况的方法最终都至少有点笨拙。也就是说,避免大多数笨拙的一种可能性是这样的:
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));
}
推荐阅读
- javascript - 如何在两个长度相同的字符串之间替换字符串
- java - 抓取 JSON 对象并将多个键值添加到变量中
- tensorflow - Tensorflow 从预训练模型中删除层
- laravel - Laravel Nova:如何扩展资源并用于自定义 Nova 工具?
- python - 在列表中值的不同列标题中打印值
- python - 更新整个工作表的单行格式
- angular - Angular 6:转移 isAdmin?从 AuthService 到 AuthGuard canActivate() 方法的值
- maven - 更新了 Maven 依赖项,但仍然收到警告
- mongodb - 不确定我的 mongo db 语句有什么问题
- git - 不允许从 git 中的分支分支