我想创建一个定义1d数组的函数,计算元素的总和,并显示该总和。 我写了下面的代码,但是我不知道使用指针和其他高级编码技术。
#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:错误:调用对象类型'int'不是函数或函数指针sum = sumofarrays(size)
I wanted to create a function that would define an 1d Array, calculate a sum of the elements, and display that sum. I wrote the following code however I'm unaware of the use of pointers and other advanced techniques of coding.
#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); }When attempting to compile this code, I get following error:
SumOfArrays.cpp:19:18: error: called object type 'int' is not a function or function pointer sum = sumofarrays(size)
最满意答案
如果只有你为你的数据使用了像std::vector<int&t; A这样的容器 。 那么你的总和会退出:
int sum = std::accumulate(A.begin(), A.end(), 0);
每个专业程序员都会立即明白你想要做什么。 这有助于使您的代码可读和可维护。
开始使用C ++标准库。 阅读一本像Stroustrup这样的好书。
If only you had used a container like std::vector<int> A for your data. Then your sum would drop out as:
int sum = std::accumulate(A.begin(), A.end(), 0);
Every professional programmer will then understand in a flash what you're trying to do. That helps make your code readable and maintainable.
Start using the C++ standard library. Read a good book like Stroustrup.
更多推荐
发布评论