找到数组中的数字总和

时间:2015-10-14 22:56:49

标签: arrays processing

我试图在Processing中找到一组数字的总和。但是当我尝试使用下面的代码计算它时,我发现自forloop运行以来值不断增加。除了添加noLoop函数或在void设置中进行添加之外,有什么办法可以得到数组中数字的总和吗?

如果有人可以帮助我,这将是一个很大的帮助。非常感谢提前

干杯,优素福。

float sum = 0;
float [] f = {12, 2, 4, 6, 23};

void setup() {

  size(600, 600);
  smooth();
}

void draw() {

  for (int i =0; i<f.length; i++) {

    sum +=f[i];
  }
  println(sum);//// I only wanted to print the first value of sum, which is the total of the numbers listed array of numbers.
}

2 个答案:

答案 0 :(得分:1)

您应该在运行循环之前重置sum变量,否则它仍将包含之前的总和。

void draw() {
  sum = 0;
  for (int i =0; i<f.length; i++) {
    sum +=f[i];
  }
  println(sum);

答案 1 :(得分:0)

声明并初始化sum作为draw函数中的局部变量而不是全局变量。这样,每次调用draw时它都会自动重置。