0

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

问题是:如果我们列出所有小于 10 且是 3 或 5 倍数的自然数,我们得到 3、5、6 和 9。这些倍数之和是 23。求所有 3 或 5 的倍数之和5 低于 1000。正确答案 = 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
4

1 回答 1

6

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

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

此外,一旦遇到 3 的倍数,第二个条件将导致循环退出,这可能不是您想要的。
一个想法可能是将其更改为for类似于 3 的倍数的循环(并将其移出第一个for循环)。

于 2013-05-11T23:25:48.333 回答