简体   繁体   English

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

[英]Write a C++ function that accepts a 1-D array and calculates the sum of the elements, and displays it

I wanted to create a function that would define an 1d Array, calculate a sum of the elements, and display that sum. 我想创建一个定义1d数组,计算元素总和并显示该总和的函数。 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) SumOfArrays.cpp:19:18:错误:调用的对象类型'int'不是函数或函数指针sum = sumofarrays(size)

If only you had used a container like std::vector<int> A for your data. 如果仅使用了std::vector<int> A类的容器作为数据。 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. 开始使用C ++标准库。 Read a good book like Stroustrup. 读一本好书,如《 Stroustrup》。

Please choose Bathsheba's answer - it is the correct one. 请选择拔示巴的答案-这是正确的答案。 That said, in addition to my comment above, I wanted to give some more tips: 就是说,除了我上面的评论之外,我还想提供一些提示:

1) You need to learn the difference between an array on the stack (such as "int A[3]") and the heap (such as a pointer allocated by malloc or new). 1)您需要了解堆栈上的数组(例如“ int A [3]”)和堆(例如由malloc或new分配的指针)之间的区别。 There's some degree of nuance here, so I'm not going to go into it all, but it's very important that you learn this if you want to program in C or C++ - even though best practice is to avoid pointers as much as possible and just use stl containers! 这里有一定程度的细微差别,因此我将不做全部介绍,但是,如果您要使用C或C ++编程,则必须学习这一点,这一点非常重要-即使最佳实践是尽可能避免使用指针,并且只需使用stl容器! ;) ;)

2) I'm not going to tell you to use a particular indentation style. 2)我不会告诉您使用特定的缩进样式。 But please pick one and be consistent. 但请选择一个并保持一致。 You'll drive other programmers crazy with that sort of haphazard approach ;) Also, the same applies to capitalization. 您会以这种随意的方法使其他程序员发疯;)同样,大写也是如此。

3) Variable names should always be meaningful (with the possible exception of otherwise meaningless loop counters, for which "i" seems to be standard). 3)变量名应始终有意义(可能存在例外,否则,无意义的循环计数器(对于“ i”来说,这是标准的))。 Nobody is going to look at your code and know immediately what "j" or "B" are supposed to mean. 没有人会看您的代码并立即知道“ j”或“ B”的含义。

4) Your algorithm, as implemented, only requires half of those variables. 4)实施的算法仅需要这些变量的一半。 There is no point to using all of those temporaries. 没有必要使用所有这些临时对象。 Just declare sum as "int sum = 0;" 只需将sum声明为“ int sum = 0;”即可。 and then inside the loop do "sum += A[i];" 然后在循环中执行“ sum + = A [i];”

5) Best practice is - unlike the old days, where it wasn't possible - to declare variables only where you need to use them, not beforehand. 5)最佳实践是-与过去不同,在过去不可能-仅在需要使用变量的地方声明变量,而不是事先声明。 So for example, you don't need to declare B or j (which, as mentioned, really aren't actually needed) before the loop, you can just declare them inside the loop, as "int B = j + A[i];" 因此,例如,您不需要在循环之前声明B或j(如上所述,实际上并不需要),您只需在循环内部声明它们即可,例如“ int B = j + A [i ];“ and "int j = B;". 和“ int j = B;”。 Or better, "const int", since nothing alters them. 更好的是“ const int”,因为没有任何改变。 But best, as mentioned in #4, don't use them at all, just use sum - the only variable you actually care about ;) 但最好的是,如#4所述,根本不要使用它们,只需使用sum-您实际上关心的唯一变量;)

The same applies to your for-loop - you should declare i inside the loop ("for (int i = ....") rather than outside it, unless you have some sort of need to see where the loop broke out after it's done (not possible in your example). 这同样适用于for循环-除非在某种情况下需要查看循环从何处中断,否则应在循环内部声明“ i”(“ for(int i = ....”)),而不是在循环外部进行声明。完成(在您的示例中是不可能的)。

6) While it really makes no difference whatsoever here, you should probably get in the habit of using "++i" in your for-loops rather than "i++". 6)尽管这里并没有什么区别,但是您应该养成在for循环中使用“ ++ i”而不是“ i ++”的习惯。 It really only matters on classes, not base types like integers, but the algorithms for prefix-increment are usually a tad faster than postfix-increment. 实际上,它仅对类有影响,与整​​数之类的基本类型无关,但是前缀递增的算法通常比后缀递增的算法快一点。

7) You do realize that you called sumOfArrays twice here, right? 7)您确实意识到自己在这里两次调用了sumOfArrays,对吗?

int sum;

int sumofarrays(A[size]);

sum = sumofarrays(A[size]);

What you really meant was: 您真正的意思是:

const int sum = sumofarrays(A);

Or you could have skipped assigning it to a variable at all and just simply called it inside your cout. 或者,您可能根本跳过了将其分配给变量的操作,而只是在cout中简单地调用了它。 The goal is to use as little code as possible without being confusing. 目标是使用尽可能少的代码不会引起混淆。 Because excess unneeded code just increases the odds of throwing someone off or containing an undetected error. 因为多余的多余代码只会增加将某人扔掉或包含未检测到的错误的几率。

Just don't take this too far and make a giant mishmash or trying to be too "clever" with one-liner "tricks" that nobody is going to understand when they first look at them! 只是不要走太远,做一个大杂烩,或者尝试用单线的“技巧”太“聪明”,当他们第一次看它们时,没人会理解! ;) ;)

8) I personally recommend - at this stage - avoiding "using" calls like the plague. 8)我个人建议-在此阶段-避免像瘟疫那样“使用”电话。 It's important for you to learn what's part of stl by having to explicitly call "std::...." each time. 重要的是,必须每次都显式调用“ std :: ....”,以了解stl的组成部分。 Also, if you ever write .h files that someone else might use, you don't want to (by force of habit) contaminate them with "using" calls that will have an effect on other peoples' code. 另外,如果您曾经编写过其他人可能使用的.h文件,则您不想(通过习惯)通过“使用”调用来污染它们,而这将对其他人的代码产生影响。

You're a beginner, that's okay - you'll learn! 您是一个初学者,没关系-您会学习! :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM