检查数组的邻居值
Checking the neighbour values of arrays
我有一个长度为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;
}
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组的地址分配给变量并删除
- 从C++本机插件更新Vector3数组
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 数组索引的值没有增加
- 将对象数组的引用传递给函数
- 为char数组调整zlib-zpipe
- 2D数组来自文本输入,中间有空格
- std::向量与传递值的动态数组
- 在c++中用vector填充一个简单的动态数组
- 使用strcpy将char数组的元素复制到另一个数组
- 使用指针从C++中的数组中获取最大值
- C++使用整数的压缩数组初始化对象
- 告诉一个 const char 数组,除了编译时 C 样式的字符串外,它不以 '