数组求和法

编程入门 行业动态 更新时间:2024-10-28 10:31:52
本文介绍了数组求和法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我的方法将求和一个数组的元素(或组件或任何您称呼它们的对象)。但是,以下代码的 a.length()部分无效。

My method will sum the elements (or components or whatever you would call them) of an array. The a.length() part of the following code doesn't work though.

public double ArraySum(double[] a) { double sum = 0; double Element; for(Element = 0; Element < a.length(); Element++) { sum = sum + a[Element]; } }

有人可以告诉我为什么.length方法突然不起作用

Could anyone tell me why the .length method suddenly doesn't work?

推荐答案

因为数组具有 length 字段,而不是长度方法。而且,按照惯例,Java变量名称以小写字母开头(方法名称也是如此; ArraySum 应该可能是 getArraySum 或 sumArray )。不需要使用 double 作为循环计数器,您可以使用 + = 。更改

Because arrays have a length field, not a length method. And, by convention, Java variable names start with a lower case letter (and so do method names; ArraySum should probably be getArraySum or sumArray). There's no need to use a double as your loop counter and you could use +=. Change

double Element; for(Element = 0; Element < a.length(); Element++) { sum = sum + a[Element]; }

类似

for(int element = 0; element < a.length; element++) { sum += a[element]; }

或,您可以使用增强的 for-each 循环,例如

or you could use an enhanced for-each loop like

for(double element : a) { //<-- for each element in the array. sum += element; //<-- add the element to the sum. }

更多推荐

数组求和法

本文发布于:2023-11-22 04:20:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1615958.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   和法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!