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;
}
答案 0 :(得分:1)
在最后一个循环中,n=0
在检查x != 0
之前执行,因此它将始终返回n = 0.这应该有效。
if(x == 0) {
break;
} else if (x > y ) {
...
} else {
...
}
答案 1 :(得分:0)
这在逻辑上是错误的:
if (x == (y + 1)) // <<<<< i think for some reason this if statement if never happening
{
应该是
if(x >= (y+1))
{
答案 2 :(得分:0)
您还需要在序列结束时重置y
变量。
答案 3 :(得分:0)
如果您只想要一个增加数字的列表,那么您的“if”条件仅测试x
等于等于而不是{{ 1}}。将条件更改为:
y
你应该有更多的运气。
答案 4 :(得分:0)
你总是返回0,因为你读取和处理的最后一个数字是0,当然,永远不会使x == (y + 1)
成为现实,所以它在退出循环之前总是执行的最后一个语句{{1 }}
答案 5 :(得分:0)
在你的程序中,你做了一些假设,你需要先验证它们。
如果这些是正确的假设,那么这里有一些调整
cout
移到循环外if (cin >> x) {...}
while
循环以阅读x
并测试x != 0
x
)开始,所以没有意义设置n
到0
。 y
必须始终为x
的当前值。如果对代码进行上述逻辑更改,则应该可以正常工作。
答案 6 :(得分:0)
我认为存在多个问题,第一个也是最重要的一个问题,您可能无法正确理解问题。根据 longest increasing subsequence 的通用定义,该输入的结果不会是6而是8。
问题比你试图实现的简单循环要复杂得多,而且通常采用Dynamic Programming技术解决。
在您的特定代码中,您试图计算if
序列的长度,每个元素恰好是最后一个读取元素的后继元素。 但是如果下一个元素不在序列中,则将长度重置为0(else { n = 0; }
),这就是给出结果的结果。您应该保留一个永远不会重置为0的max
值,例如添加if
块:max = std::max( max, n );
(或纯C:max = (n > max? n : max );
。然后结果将是max
值。