我有一个长度为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;
}https://stackoverflow.com/questions/50611993
复制相似问题