再见程序员。我必须设计一个 C++ 程序,该程序读取以零结尾的正整数值序列,并找到给定序列中最长递增子序列的长度。例如,对于以下 整数序列:
1 2 3 4 5 2 3 4 1 2 5 6 8 9 1 2 3 0
程序应该返回 6 我写的代码看起来是正确的,但由于某种原因总是返回零,有人可以帮我解决这个问题。
这是我的代码:
#include <iostream>
using namespace std;
int main()
{
int x = 1; // note x is initialised as one so it can enter the while loop
int y = 0;
int n = 0;
while (x != 0) // users can enter a zero at end of input to say they have entered all their numbers
{
cout << "Enter sequence of numbers(0 to end): ";
cin >> x;
if (x == (y + 1)) // <<<<< i think for some reason this if statement if never happening
{
n = n + 1;
y = x;
}
else
{
n = 0;
}
}
cout << "longest sequence is: " << n << endl;
return 0;
}
最佳答案
在你的程序中,你做了一些假设,你需要先验证它们。
- 子序列总是从 1 开始
- 子序列总是递增 1
如果这些假设是正确的,那么这里有一些调整
- 将
cout
移出循环 - C++ 中测试来自流的输入操作是否有效的规范方法是简单地测试正在运行的流,即
if (cin >> x) {...}
< - 鉴于上述情况,您可以重新编写
while
循环以读取x
并测试x != 0
- 如果以上条件都成立,进入循环
- 现在给出上述假设,您的第一次检查是正确的,但是如果检查失败,请记住新的子序列从当前输入数字(值
x
)开始,所以没有sense 将n
设置为0
。 - 无论哪种方式,
y
必须始终是x
的当前值。
如果您对代码进行上述逻辑更改,它应该可以工作。
关于C++读取整数序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5894121/