当我使用while循环时,为什么我的代码不起作用?

时间:2013-05-11 23:22:21

标签: java

今晚我正在处理来自http://projecteuler.net/problem=1的问题1。它不能使用while循环。我确实使用两个short cut if语句来使用它。在正确解决之后,我在论坛上看到有更好的解决方案使用数学,但我是新手,需要了解我的while循环出了什么问题。

以下是问题: 如果我们列出10以下的所有自然数是3或5的倍数,我们得到3,5,6和9.这些倍数的总和是23.找到低于1000的3或5的所有倍数的总和。正确答案= 233168

    public class Project1_Multiples_of_3_and_5 {
//Main method
public static void main (String args[])
{   
    int iResult = 0;

    for (int i = 1; i <= 1000 / 3; i++)  // for all values of i less than 333 (1000 / 3)
    {
        iResult += i * 3;  // add i*3 to iResults
        //the short cut if below works but I want to use a while loop
                //iResult +=  (i % 3 !=0 && i < 1000 / 5) ? i * 5 : 0;  // add i*5 to iResults excluding the multiples 3 added in the previous step while i < 200 ( 1000 / 5 )

        while ( (i < 1000 / 5) && (i % 3 != 0) )
        {
            iResult += i * 5;
/************************************************************************************
SOLVED!!! ... sort of
adding a break makes the code work but defeats the purpose of using a loop.  I guess     I    should just stick with my 2 if statements
************************************************************************************/

                        break;
        }//end while
    }// end for

    System.out.println(iResult);

    }//end main method
}//end class

1 个答案:

答案 0 :(得分:6)

您的while循环永远不会终止,因为您永远不会在结束条件中更改变量(i):

while ( (i < 1000 / 5) && (i % 3 != 0) )
{
    iResult += i * 5; // i is not updated here
}//end while

此外,第二个条件将导致循环在遇到3的倍数时立即退出,这可能不是您想要的。
一个想法可能是将此更改为for循环,就像您对3的倍数所使用的循环(并将其移出第一个for循环)。

相关问题