给定一个整数数组,求其元素之和。错误在哪里?
出于某种原因,我没有得到想要的答案,我无法理解错误在哪里。
例如,给定数组ar = [1,2,3], 1+2+3 = 6,所以返回6,但我得到了650462183。
#include <iostream>
#include <algorithm>
#include <vector>
#include <ctime>
#include <cstdlib>
#include <cctype>
using namespace std;
int main ()
{
int i;
cout << "enter the value of i" << endl;
cin >> i;
int arr[i];
cout << "enter the value of yout arrn";
cin >> arr[i];
int count = 0;
for (int j = 0; j <= i; j++)
{
count += arr[j];
}
cout << count << endl;
return 0;
}
回答
该数组int arr[i];只有i元素:arr[0]to arr[i-1]。
因此,循环的条件应该是j < i,而不是j <= i。
cin >> arr[i];也是错的。您应该使用另一个循环来读取i元素,而不是像这样只读取一个超出范围的元素。
#include <iostream>
#include <algorithm>
#include <vector>
#include <ctime>
#include <cstdlib>
#include <cctype>
using namespace std;
int main ()
{
int i;
cout << "enter the value of i" << endl;
cin >> i;
int arr[i];
cout << "enter the value of yout arrn";
for (int j = 0; j < i; j++)
{
cin >> arr[j];
}
int count = 0;
for (int j = 0; j < i; j++)
{
count += arr[j];
}
cout << count << endl;
return 0;
}
请注意,标准 C++ 不支持变长数组 (VLA) 之类的int arr[i];。你应该std::vector改用。在这种情况下,您可以通过更改int arr[i];为来执行此操作std::vector<int> arr(i);。
另一种选择是不使用数组并直接对输入的内容求和:
#include <iostream>
#include <algorithm>
#include <vector>
#include <ctime>
#include <cstdlib>
#include <cctype>
using namespace std;
int main ()
{
int i;
cout << "enter the value of i" << endl;
cin >> i;
cout << "enter the value of yout arrn";
int count = 0;
for (int j = 0; j < i; j++)
{
int element;
cin >> element;
count += element;
}
cout << count << endl;
return 0;
}