我只是想打印一定上限内的完美数字,但我得到了其他显示的数字,它们不是完美的数字。我并不是试图使用一种方法,而不仅仅是主循环中的所有内容。我需要一些帮助。
public static void main(String arg[]) {
int upper;
int sum = 0;
int i;
System.out.println("Enter upper limit");
Scanner stnd = new Scanner(System.in);
upper = stnd.nextInt();
for(int n = 1; n < upper; n++) {
i = 1;
sum = 0;
while (i <= n/2) {
if (n%i == 0) {
sum = sum + i;
}
i++;
if(sum == n) {
System.out.println(n+" is a perfect number");
break;
} else {
}
}
}
}
最佳答案
您的代码中有一个 while
循环,用于将数字的因数相加。问题是,当 while
循环尚未完成时,您正在检查总和。在 24 的情况下,您已将其相加
1 + 2 + 3 + 4 + 6 + 8
这是 24,但你的循环还没有达到 12。
你需要移动
if(sum == n) {
System.out.println(n+" is a perfect number");
}
到 while
循环之后,而不是将其放在循环内。
关于java - 尝试在java中找到上限内的完美数字而不创建方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69474338/