gpt4 book ai didi

c++ - 编写一个接受一维数组并计算元素总和并显示它的 C++ 函数

转载 作者:行者123 更新时间:2023-11-30 01:12:26 25 4
gpt4 key购买 nike

我想创建一个函数来定义一维数组、计算元素的总和并显示该总和。我编写了以下代码,但我不知道指针的使用和其他高级编码技术。

#include <iostream>

using namespace std;


int main()
{
int size;
int A[];

cout << "Enter an array: \n";
cin << A[size];

int sum;

int sumofarrays(A[size]);

sum = sumofarrays(A[size]);
cout << "The sum of the array values is: \n" << sum << "\n";
}


int sumofarrays(int A[size])
{
int i;
int j = 0;
int sum;
int B;

for (i=0; i<size; i++)
{
B = j + A[i];
j = B;
}

sum = B;
return(sum);
}

尝试编译这段代码时,出现以下错误:

SumOfArrays.cpp:19:18: error: called object type 'int' is not a function or function pointer sum = sumofarrays(size)

最佳答案

要是你用了像std::vector<int> A这样的容器就好了为您的数据。然后你的总和会下降为:

int sum = std::accumulate(A.begin(), A.end(), 0);

然后每个专业程序员都会立刻明白您要做什么。这有助于提高代码的可读性和可维护性。

开始使用 C++ 标准库。读一本像 Stroustrup 这样的好书。

关于c++ - 编写一个接受一维数组并计算元素总和并显示它的 C++ 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34262931/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com