【问题标题】:Length of a growing sequence C++ [closed]增长序列C ++的长度[关闭]
【发布时间】:2014-01-25 22:57:03
【问题描述】:
#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;
}

我的评论技巧很烂,所以不要对我太苛刻。我试图尽可能清楚地解释我想用我的代码完成什么,因为我之前的问题中存在误解。

TL;DR: 总而言之,这是(或至少应该是)一个程序,它找到数组中“增长”数字的最长序列长度。 “成长”是什么意思?一个序列,其中每个下一个数字都比前一个数字偶数或大。例如在1 2 3 3 1 2 中,“增长”序列是1 2 3 3,它的长度(输出应该是什么)是4。但是,由于某种未知的原因,当我编译并输入数组时,程序冻结而没有给出任何输出。 。 曾经。有什么想法可能导致这种情况吗?提前感谢您的帮助!

【问题讨论】:

  • 在调试器中单步调试程序。
  • 欢迎来到 Stack Overflow!要求人们发现代码中的错误并不是特别有效。您应该使用调试器(或添加打印语句)来隔离问题,方法是跟踪程序的进度,并将其与您期望发生的情况进行比较。一旦两者发生分歧,你就发现了你的问题。 (然后如果有必要,你应该构造一个minimal test-case。)
  • @OliCharlesworth 哦,那我真的很抱歉。谢谢,但我应该怎么处理我的问题?删除它还是什么?我不希望仅仅因为这个而遭到大量的反对。

标签: c++ arrays numbers sequence


【解决方案1】:

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

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

【讨论】:

  • 上帝,你救了你一命!非常感谢。真的很抱歉给您带来这样的担忧,但我对编程真的太陌生了,并且在尝试使用调试器时发现了太多麻烦。
  • 在上面的 cmets 中还提到的一件事是,如果你不想使用调试器(当你第一次开始编程时肯定会感到困惑!),试着放大量的 @987654323 @s 在您的代码中,并在不同点输出不同变量的值。然后,确保它们符合您的预期。无论如何,这基本上就是调试器为您所做的,只是更漂亮^^
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-12
  • 1970-01-01
相关资源
最近更新 更多