如何执行一个int []数组的总和 [英] How to perform a sum of an int[] array

查看:306
本文介绍了如何执行一个int []数组的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个数组的10 整数 A ,初始化名为总和一个局部变量并使用循环来查找所有数字的总和在阵列中 A

Given an array A of 10 ints, initialize a local variable called sum and use a loop to find the sum of all numbers in the array A.

这是我的回答,我提交了:

This was my answer that I submitted:

sum = 0;
while( A, < 10) {
   sum = sum += A;
}

我没有得到在这个问题上的任何点。我做了什么错了?

I didn't get any points on this question. What did I do wrong?

推荐答案

您的语法和逻辑是在许多方式不正确。您需要创建一个索引变量,并使用它来访问数组的元素,像这样:

Your syntax and logic are incorrect in a number of ways. You need to create an index variable and use it to access the array's elements, like so:

int i = 0;        // Create a separate integer to serve as your array indexer.
while(i < 10) {   // The indexer needs to be less than 10, not A itself.
   sum += A[i];   // either sum = sum + ... or sum += ..., but not both
   i++;           // You need to increment the index at the end of the loop.
}

上面的例子使用了,而循环,因为这是你采取的方法。一个更合适的结构将是一个循环,在波格丹的答案。

The above example uses a while loop, since that's the approach you took. A more appropriate construct would be a for loop, as in Bogdan's answer.

这篇关于如何执行一个int []数组的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆