c++ - 检查数组的相邻值
问题描述
我有一个长度为数字的数组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;
}
解决方案
当 时i = 0
,表达式Bush[i-1]
导致访问数组的无效位置(- 1)
。
同样,当i = total - 1
(迭代的最后一个索引)时,表达式 Bush[i+1]
会为您提供一个total
超出数组范围的索引。
推荐阅读
- python - How to conditionally replace values in a dataframe?
- python - 安装python包时出错。为什么我得到这个错误?
- python - 在 matplotlib 中更改 ax.text 的字体
- php - PHP MYSQL 问题:无法使用 $resultDetails->fetch_assoc 获取数据库信息
- python - Python opencv cv2.VideoCapture.read() 第一次运行后无限期卡住
- c# - 有没有办法在 for C# 中读取多个文本框
- python - 熊猫按小时分组按天计算
- javascript - 单击按钮时如何运行此功能?
- facebook-graph-api - Facebook Graph API 资源管理器不返回 Facebook 照片 如何解决此问题?
- kentico - 按父节点 guid 获取所有子节点的列表