首页 > 解决方案 > 检查数组的相邻值

问题描述

我有一个长度为数字的数组L,我必须让程序检查每个数组元素及其前后邻居的总和。

因此,例如,如果我的数组是{1, 2, 3},则第二个元素的输出应该是6因为1 + 2 + 3 = 6它们都是邻居。

如果所选元素是数组中的第一个元素,则其前面的邻居是数组的最后一个元素,如果该元素是数组中的最后一个元素,则后面的邻居是数组的第一个元素。所以,在这个{1, 2, 3}例子中,无论你检查什么数字,你总是得到6,但如果是这样{1, 2, 3, 4},第三个元素的答案就是9因为3 + 2 + 4 = 9

我希望你明白它应该如何工作。

我遇到的问题是输出失控。我试图检查阵列本身,这是完全正常的。在{1, 2, 3}示例中,我得到了一个输出,7208681但我不知道为什么。

#include <iostream>

using namespace std;

int main()
{
    int total;
    cin >> total;
    int Bush[total]; //array of numbers

    int temp, output = 0; //output variable and a container for the last resurt a.k.a temp

    for (int i = 0; i <= total - 1; i++)
    {
        cin >> Bush[i]; //inputting the array elements
    }
    for (int i = 0; i < total; i++)
    {
        if (i == 0)
            output = Bush[i] + Bush[i + 1] + Bush[total]; //checking if the loop checks the first number
        if (i == total - 1)
            output = Bush[i] + Bush[0] + Bush[i - 1]; //checking if the loop checks the first number

        temp = output;                                //assigning the temp value to the current output value
        output = Bush[i] + Bush[i + 1] + Bush[i - 1]; //assigning a new output value

        if (temp > output)
            output = temp; //checking values
    }

    cout << output << endl; //outputting
    return 0;
}

标签: c++arrays

解决方案


当 时i = 0,表达式Bush[i-1]导致访问数组的无效位置(- 1)

同样,当i = total - 1(迭代的最后一个索引)时,表达式 Bush[i+1]会为您提供一个total超出数组范围的索引。


推荐阅读