检查数组的邻居值

Checking the neighbour values of arrays

本文关键字:邻居 数组 检查      更新时间:2023-10-16

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

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

如果所选元素是数组中的第一个元素,则其前一个相邻元素是数组的最后一个元素,如果该元素是数组中的最后一个元素,则下一个相邻元素是数组的第一个元素。 因此,在{1, 2, 3}示例中,无论您检查什么数字,您总是会得到6,但如果它是{1, 2, 3, 4}的,则第 3 个元素的答案将是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;
}

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

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

Bush的最后一个元素位于索引total -1处,但Bush[total]您在i==0

最后,你的代码中有很多错误,尽管如此,if/else 结构的问题。

我建议您使用另一个基于模块运算符的内部循环,该模块运算符大大简化了代码:

int max = 0;
for(int i = 0; i<total; i++)
{
output = Bush[i] + Bush[(i+1)%total] + Bush[(i-1+total)%total];
if(max < output) max = output;//checking the max
}
cout<<max<<endl;//outputting

这将执行您需要的操作。

希望这可能会有所帮助。

我认为下面的代码可以工作

int main()
{
int total;
cout << "Enter Number of Elements " << endl;
cin>>total;
int Bush[total];//array of numbers
int temp = 0, output = INT_MIN; //output variable and a container for the last resurt a.k.a temp
cout << "Enter the Elements " << endl;
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)
temp = Bush[i] + Bush[i+1] + Bush[total -1];//checking if the loop checks the first number
else if(i == total - 1)
temp = Bush[i] + Bush[0] + Bush[i-1];//checking if the loop checks the first number
else
temp = Bush[i] + Bush[i+1] + Bush[i-1]; //assigning the temp value to the current output value
output = (temp > output)?temp:output;
}
cout<<output<<endl;//outputting
return 0;
}