【发布时间】:2020-06-09 19:49:22
【问题描述】:
我要为课堂写作业,但被卡住了,不知道如何让它像预期的那样正确设置。我很感激我得到的任何帮助谢谢。这是作业:
一个整数被称为一个完美数,如果它的因数, 包括 1(但不包括数字本身),求和。为了 例如,6 是一个完美数,因为 6=1+2+3。写法完美 确定 number 是否为完美数。在 确定并显示所有完美数字的应用程序 介于 2 和 1000 之间。显示每个完美数的因数 确认这个数字确实是完美的。
输出:
6 is perfect.
Factors:1 2 3
28 is perfect.
Factors: 1 2 4 7 14
496 is perfect.
Factors: 1 2 4 8 16 31 62 124 248
这是我遇到的代码:
public class Homework4 {
public static void main(String[] args) {
for(int num=2;num<=1000;num++)
{
if(perfect(num))
{
System.out.println(num + " is perfect.");
System.out.printf("Factors: ",perfect(num));
}
}
}
public static Boolean perfect(int num)
{
int sum = 0;
for(int i=1;i<num;i++)
{
if (num % i == 0)
{
sum+=i;
}
}
if(num==sum)
{
for(int i=1;i<num;i++)
{
if (num % i == 0)
{
System.out.print(i+" ");
}
}
}
return sum==num;
}
}
运行:
1 2 3 6 is perfect.
1 2 3 Factors: 1 2 4 7 14 28 is perfect.
1 2 4 7 14 Factors: 1 2 4 8 16 31 62 124 248 496 is perfect.
1 2 4 8 16 31 62 124 248 Factors: BUILD SUCCESSFUL (total time: 0 seconds)
【问题讨论】:
-
除了我猜想的地方没有显示的“因素”
-
如果是这个问题,那是因为你在 if 之前调用了 perfect(num) 所以它在完美数之前输出因子,然后我怀疑 printf(a, b)
-
是的,这就是问题所在。那么我将如何修复程序的顺序以使其与我显示的输出一样?
-
你最终得到正确的输出了吗?
-
抱歉,回复晚了,但我从来没有得到正确的输出,但我的教授让程序滑动,因为我做对了。
标签: java methods perfect-numbers