gpt4 book ai didi

java - java中的完美数使用方法做作业

转载 作者:太空宇宙 更新时间:2023-11-04 14:20:21 24 4
gpt4 key购买 nike

我要为类写作业,但被困住了,不知道如何正确设置它,就像它应该的那样。我很感谢我得到的任何帮助,谢谢。这是作业:

An integer number is said to be a perfect number if its factors, including 1 (but not the numbers itself), sum to the number. For example,6 is a perfect number, because 6=1+2+3. Write method Perfect that determines whether number is a perfect number. Use this method in an application that determines and displays all the perfect numbers between 2 and 1000. Display the factors of each perfect number to confirm that the number is indeed perfect.

输出:

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)

最佳答案

有两种方法可以解决此问题。

  • 您可以将 perfect 方法分解为两个单独的方法 - 一种方法检查数字是否完美,另一种方法打印其因子。检查时调用第一个 - 如果返回 true,则调用第二个。

或者

  • 您可以将打印 ... is Perfect 的行移动到方法本身中。然后从 main 中删除整个 if block 。

关于java - java中的完美数使用方法做作业,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27261104/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com