Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/127.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/jquery-ui/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 我的c++;用于对数组元素进行求和的代码不';我不能正常工作_C++ - Fatal编程技术网

C++ 我的c++;用于对数组元素进行求和的代码不';我不能正常工作

C++ 我的c++;用于对数组元素进行求和的代码不';我不能正常工作,c++,C++,我已经编写了一些代码来添加数组的所有元素并显示结果,但是它工作不正常,可能出了什么问题 我尝试了2-5个元素,但唯一给出正确结果的是有2个元素的 #include <iostream> using namespace std; int main() { int n, sum=0; int arr[n]; \\no of array elements cout<<"enter the number of array elements\n";

我已经编写了一些代码来添加数组的所有元素并显示结果,但是它工作不正常,可能出了什么问题

我尝试了2-5个元素,但唯一给出正确结果的是有2个元素的

#include <iostream>

using namespace std;

int main() {
    int n, sum=0;
    int arr[n]; \\no of array elements
    cout<<"enter the number of array elements\n";
    cin>>n;
    cout<<"enter the array elements\n";
    for(int i=0; i<n; i++)
    {
        cin>>arr[i];    \\got my array filled
    }
    cout<<"calculating the sum...\n";
    for(int i=0; i<n; i++)
    {
        sum=arr[i]+arr[i-1];
    }
    cout<<"the answer is:\n"<<sum;    \\i think the problem is in this loop
    return 0;
}
#包括
使用名称空间std;
int main(){
int n,和=0;
int arr[n];\\n数组元素数
coutn;
这个问题在我们的讨论中。
出于某种原因,您要减去
arr[i]
arr[i-1]
并将其加到总和上

2个元素起作用,因为如果你取
i=1
,i-1=0。所以你将
arr[0]
arr[1]
相加,它们都是数组的元素

如果要对数组中的所有元素求和,只需执行
SUM+=arr[i];
(在adding for中)

此外,您正在将sum设置为
arr[i]-arr[i-1]
,而没有对其进行求和。

问题1:

int n, sum=0;
int arr[n]; //no of array elements
您希望以n作为数组的初始值,但此n未定义。 所以,你可以写它

int n, sum=0;
cout<<"enter the number of array elements\n";
cin>>n;
int arr[n]; //no of array elements
sum=arr[i]+sum;
在每次迭代中,您只添加了当前数组值和上一个数组值。您的代码还希望访问arr[-1]地址。:D

所以,你可以写它

int n, sum=0;
cout<<"enter the number of array elements\n";
cin>>n;
int arr[n]; //no of array elements
sum=arr[i]+sum;

在每次迭代中,arr[i]与上一次的总和相加。

int n;int arr[n]可变长度数组不是标准C++ C++。如果你选择使用它们,你需要确保你使用的变量长度实际上是在数组声明的点上初始化的。你不能让数组在以后改变大小变量,并期望i不要更改任何内容。无关:在为一个问题编写标题时,尽量使其具有描述性,并有助于那些关注你的问题并能从你的问题中学习的人。建议:不要包含诸如“不正确”之类的内容,因为这是隐含的。如果代码正确,你就不会提出问题。使用
std::vector
进行动态分析你知道,C++中的注释导入器是“代码> //< /代码>,不是\\”尼尔ButtValm,实际上,我从给定的代码中复制。谢谢你的纠正。对不起,这是我的坏……我实际上不评论我的代码,只是为了解释一下…