在for循环中添加值

时间:2011-02-27 23:40:10

标签: c for-loop

int n, total, array[4] = {5,4,2,7}

for (n =0; n<4; n++)
{
total = array[n] + array[n+1];
}

5 + 4 = 9 + 2 = 11 + 7 = 18

我知道我需要将sum的值存储到变量中,但是如何将变量循环添加回数组中的下一个数字。

3 个答案:

答案 0 :(得分:5)

int n, total = 0, array[4] = {5,4,2,7}

for (n =0; n<4; n++)
{
  total += array[n];
}

答案 1 :(得分:3)

您不必添加数组+ 1位置。只需要在一个变量中累加值

// Declaration of total variable and values array
int total=0, array[4]={5,4,2,7}

// For loop
for (int n=0; n<4; n++) {
    // Total accum
    total+=array[n];
    // Use += or you can use too this: total=total+array[n];
}

答案 2 :(得分:1)

您的代码集

total = array[0] + array[1] - &gt; 9

然后

total = array[1] + array[2] - &gt; 6

然后

total = array[2] + array[3] - &gt; 9

然后

total = array[3] + array[4] - &gt;未定义的行为

当然不是你想要的。你问

  

我知道我需要存储该值   将总和变成变量但是怎么做   我让变量循环回来了   添加到数组中的下一个数字。

嗯,变量是total,你想把它添加到数组中的下一个数字;这只是

total = total + array[n]

(或total += array[n])。

剩下的就是初始化total = 0,以便第一次添加(total = total + array[0])将total设置为array[0]而不是某些未定义的值。