首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >检查数组的邻近值

检查数组的邻近值
EN

Stack Overflow用户
提问于 2018-05-31 03:17:48
回答 4查看 546关注 0票数 1

我有一个长度为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的输出,但我不知道为什么。

代码语言:javascript
复制
#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;
}
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50611993

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档