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添加值在for循环中
我知道我需要之和的值存储到一个变量,但如何让我的变量循环返回被添加到数组中的下一个数字。
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添加值在for循环中
我知道我需要之和的值存储到一个变量,但如何让我的变量循环返回被添加到数组中的下一个数字。
int n, total = 0, array[4] = {5,4,2,7}
for (n =0; n<4; n++)
{
total += array[n];
}
你不必做array + 1的位置添加。只需要ACCUM在一个变量中的值
// 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];
}
你的代码设置
total = array[0] + array[1]
- > 9
然后
total = array[1] + array[2]
- > 6
然后
total = array[2] + array[3]
- > 9
然后
total = array[3] + array[4]
- >未定义行为
。你问
我知道,我需要和的值 存储到一个变量,但怎么做 我使可变环回是 添加到阵列中的下一个号码。
那么,变量是total
,并且您想要将它添加到数组中的下一个数字;这只是
total = total + array[n]
(或total += array[n]
)。
剩下的就是初始化total = 0
使得第一附加(total = total + array[0]
)设置total
到array[0]
,而不是一些不确定的值。
忘记了复合赋值 – 2011-02-27 23:45:16
@thao nguyen:复合赋值在这里没什么特别的,你也可以写成'total = total + array [n]'。左边的“total”是赋值前变量的值。 – kriss 2011-02-28 00:05:44