[英]Why does this not work when trying to find the sum of all multiples of 3 and 5 in 1000?
There are a lot of questions on here about the project Euler question about finding the sum of all the multiples of 3 and 5 below 1000, but I am a beginner at Java , and I attempted to make my own program to try and figure this out.The problem with my code is, it keeps giving the answer 466
. 关于项目Euler的问题,这里有很多问题,涉及寻找1000以下3和5的所有倍数之和,但是我是Java的初学者,所以我尝试制作自己的程序来尝试解决这个问题我的代码的问题是,它不断给出答案
466
。 466 is the wrong answer to this problem, so I'm wondering what I did wrong. 466是对这个问题的错误答案,所以我想知道自己做错了什么。
Here is my code. 这是我的代码。
package sumofmultiples;
public class sumofMultiples{
public static void main(String[] args){
int number = 1; //<- This is the number that we are checking to be a multiple.
int totalNumber= 0; //<- Total number of multiples counted so far.
while (number < 1000){
if ((number % 3) == 0){
totalNumber++;
//The number is a multiple of 3.
} else if ((number % 5) == 0){
totalNumber++;
//The number is a multiple of 5
}
number++; //<- Move on to the next number.
}
System.out.println(totalNumber); //<- Print results
}
}
You are calculating the number of multiples. 您正在计算倍数。 Not their sum.
不是他们的总和。 The totalNumber++ is going to be incremented whenever a number is a multiple of 3 or 5, but the 'multiple' is not stored.
每当数字是3或5的倍数时,totalNumber ++都会增加,但是不会存储“ multiple”。
Change totalNumber++
to totalNumber += number
and your problem is solved. 将
totalNumber++
更改为totalNumber += number
解决问题。
package sumofmultiples;
public class sumofMultiples{
public static void main(String[] args){
int number = 1; //<- the number that we are checking to be multiple.
int totalNumber= 0; //<- Total number of multiples counted so far.
while (number < 1000){
if ((number % 3) == 0 || (number % 5) == 0){
totalNumber += number;
}
number++; //<- Move on to the next number.
}
System.out.println(totalNumber); //<- Print results
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.