解决这个问题需要大量的逻辑评估。所以,我们需要很多布尔表达式和 if 语句。
解决方案的一个关键是跟踪 2 个值:
我们总是可以比较这些值,然后做出决定。问题是我们一开始没有“以前的”值。所以,我们需要做一个特殊的处理,首先从用户那里读取一个值,并将其存储为上一个值,然后总是在循环中读取一个当前值。
在循环结束时,我们会将当前值赋给“previuosValue”。然后在下一次循环运行中,我们总是只需要从用户那里读取当前值。
蚂蚁这两个值,我们可以在一个while循环中比较。
我们将当前值与之前的值进行比较,并根据结果定义一个“方向”标志以进行进一步比较。
这是我们在读完第二个数字后做的。之后,方向总是确定的,永远不会改变。
例如,如果当前值大于上一个值,那么在下一个循环中,下一个值必须更小。反之亦然。
例子:
第二个值大于第一个值。因此,对于我们期望的下一个值
小 --> 大 --> 小 --> 大 --> 小 --> 大 --> 。 . .
等等。这永远不会改变。
反之亦然。
第二个值小于第一个值。因此,对于我们期望的下一个值
大 --> 小 --> 大 --> 小 --> 大 --> 小 --> 大 --> 。 . .
在处理完“下一个”数字后,方向标志总是会反转。
然后我们可以在下一次循环运行中评估停止条件。比较是否会产生我们期望的值和方向?
如果不是,或者如果值相等,那么我们停止输入。
当然,我们不会在第一个循环中进行这种评估,因为那样的话,我们总是有一个有效的对,然后再计算方向。
所以,你看。我们总是只需要 2 个变量。
与往常一样,有许多可能的实现方式。请参阅以下示例以获取解决方案:
#include <iostream>
int main() {
// Read initial previous number (The first number)
if (int previousNumber{}; std::cin >> previousNumber) {
// Flag that indicates, if we should continue reading new numbers or not
bool continueToRead{ true };
// First number needs special treatment, there is no other number
bool firstCheck{ true };
// The "direction" of the comparison
bool nextNumberMustBeSmaller{false};
// Read numbers in a loop
while (continueToRead) {
// Read current (next) number
if (int currentNumber{}; std::cin >> currentNumber) {
// After heaving read the first value in the loop, we can detect the direction
if (firstCheck) {
// Get the "direction" of the comparison for the next numbers
// If the number is bigger than last number
if (currentNumber > previousNumber)
// Then next value muste be smaller
nextNumberMustBeSmaller = true;
// If this number is smaller
else if (currentNumber < previousNumber)
// then next number must be bigger
nextNumberMustBeSmaller = false;
else
continueToRead = false;
// First check has been done
firstCheck = false;
}
else {
// Find out the stop condition
if (
// Direction is smaller but number is bigger or
(nextNumberMustBeSmaller and (currentNumber > previousNumber)) ||
// Direction is bigger but number is smaller or
(not nextNumberMustBeSmaller and (currentNumber < previousNumber)) ||
// Or numbers are equal
(currentNumber == previousNumber)) {
// Then: Stop reading values
continueToRead = false;
}
nextNumberMustBeSmaller = not nextNumberMustBeSmaller;
}
// Remember the last value. So, for the next loop rund, the current value will become the previous one
previousNumber = currentNumber;
}
else {
std::cerr << "\n\nInvalid input\n\n";
continueToRead = false;
}
}
}
else std::cerr << "\n\nInvalid input\n\n";
return 0;
}
在启用 C++17 的情况下进行编译。