2014-01-25 104 views
0
#include <iostream> 
using namespace std; 

const int MAX_SIZE = 20; 

int main() 
{ 
    int n, a[MAX_SIZE]; // initialize array and its size 
    cin >> n;      // 
    for (int i = 0; i < n; i++)  // ===> array input 
     cin >> a[i];    // 
    int max = 0; // initializing a variable indicating the length of the longest sequence 
    int i; 
    int current = 0; // makes sure the each loop begins from where the last has concluded 
    do 
    { 
     int count = 0; // counter indicating the length of the sequence.. resets after each loop 
     for (i = current; a[i] <= a[i + 1] && i < n - 1; i++) // loops until a lower than the previous number is found or the array ends 
     { 
      count++; 
     } 
     current = i; // makes so that the next loop can start from where the last has concluded 
     if (count > max) max = count; // determines the longest "growing" sequence of numbers 
    } while (i < n); // when all of the array elements are checked the program is done 
    cout << max << endl; 
    return 0; 
} 

我的评论技巧很糟糕,所以对我来说不要太难。我试图尽可能清楚地解释我想用我的代码完成的事情,因为我之前的问题中存在误解。长度不断增长的序列C++

TL; DR:总结起来,这是(或至少应该是)一个程序,它可以在数组中找到“增长”数字的最长序列长度。 “增长”意味着什么?每一个下一个数字均等于或高于前一个数字的顺序。例如在1 2 3 3 1 2中,“增长”序列为1 2 3 3,其长度(输出结果应该是4)。然而,由于某种未知的原因,当我编译并输入数组时,程序冻结而没有给出任何输出。任何想法可能导致什么?我在这里先向您的帮助表示感谢 !

+2

在调试器中逐步执行程序。 –

+2

欢迎来到Stack Overflow!要求人们发现代码中的错误并不是特别有效。您应该使用调试器(或者添加打印语句)来分析问题,追踪程序的进度,并将其与预期发生的情况进行比较。只要两者发生分歧,那么你就发现了你的问题。 (然后如有必要,你应该构建一个[最小测试用例](http://sscce.org)。) –

+0

@OliCharlesworth哦,我真的很抱歉。谢谢,但我该怎么处理我的问题?删除它或什么?我不想因为这一点而大量涌现。 – user3213110

回答

1

该行current = i;是错误的。您应该从之后的元素开始。还有一个,但是一旦你修复这个问题,它会更容易找到。这两个错误都可以通过在propper地方添加+1来解决。

请注意,你真的应该使用调试器,像其他人暗示。它可能会在一分钟内解决你的问题。请下次再做! :)

+0

上帝,你是救命恩人!非常感谢。我真的很抱歉让你担心这样的担忧,但是我对编程感到太新了,并且尝试使用调试器时遇到了太多麻烦。 – user3213110

+0

在上面的评论中还提到了一件事,如果你不想使用调试器(当你第一次开始编程时肯定会感到困惑!),试着在你的代码中加入大量的'cout',输出不同点的不同变量的值。然后,确保它们与你所期望的相符。这基本上是调试器为你做的,只是更漂亮^^ –