-5
public class problem1 {
    public static void main(String args [])
    {
    int [] a = new int [1000];

    for (int counter = 0; counter<=a.length;counter++);
    { 
        if ((counter % 3 == 0) || (counter % 5 == 0))
        {
            int temp += counter;
        }
    }

}
}

我正在尝试解决一个方程式,您必须通过一个包含数字 1-1000 的数组,并将所有 3 和 5 的倍数的数字相加,但我的代码不会执行。谁能看到我的错误?

4

4 回答 4

4

您的代码有两个主要问题:

  • 在 for 循环的末尾有一个分号。

    for (int counter = 0; counter<=a.length;counter++); // Remove the ;
    
  • 您每次都在 for 循环中重新声明变量。

    int temp += counter;  // replace it with `temp += counter`.
    

temp并在 ,之外声明变量for loop,并使用它的默认值0

一个小问题是:

  • 你不需要那个数组 a。而是用所需的值声明一个int变量(在本例中为)。并在循环条件下使用它,而不是.total1000a.length
于 2013-02-13T20:31:54.767 回答
1
  • 不要为您的计数器创建数组。没有必要,数组通常存储可重用的值,例如姓名、城市、年龄等。

  • 同样 for 循环也不以分号结尾。

  • 最重要的是:不要在循环中声明变量。如果你这样做,你将一次又一次地创建 X 次变量

public class problem1 {


public static void main(String[] args) {

    int temp = 0;

    for (int i = 0; i <= 1000; i++)

    {
        if ((i % 3 == 0) || (i % 5 == 0)) {
            temp += i;

        }
    }
    System.out.println("Result is :" + temp);
}

}
于 2013-02-13T20:38:37.637 回答
0

由于 for 末尾的分号,您的代码将永远不会执行,它不会给您编译错误,但这意味着一个空语句,因此永远不会执行 for 主体,只需删除分号即可。

于 2013-02-13T20:35:02.973 回答
0

int temp我相信您应该首先在 for 循环之外进行初始化。它应该如下:int temp = 0;然后temp += counter;应该工作。

于 2013-02-13T20:35:16.163 回答