Can you help me with java?

2015-11-03 8:28 pm
How can I access into arrays and add them each other then divide them?
example:
int[] a = {1,2,3,4};
now I want to add 1+2+3+4
Thanks in advance for the help

回答 (3)

2015-11-03 8:47 pm
Use the length property to determine the size of the array. Use [] notation to access an element. Use a for loop to add them up.

for (int i = 0; i < a.length; i++)
{
sum += a[i];
}
2015-11-03 8:45 pm
you can create an intermediate int

int tempValue = 0

foreach(var item in a)
{
tempValue = item + tempValue;
}

int devidedValue = tempValue/a.Count();
2015-11-03 9:55 pm
To access the nth object in array "a", use a[n]

To access every object in the array, use a "for" loop, incrementing n.

int sum = 0;
for (int i = 0; i < a.length; i++)
sum += a[i];


收錄日期: 2021-05-01 00:38:36
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20151103122802AAgxMta

檢視 Wayback Machine 備份