Hellooo我试图显示用户输入的1到和整数及其因子之间的所有完美数字。我得到的代码工作正常,这只是我的输出不完全匹配我想要的输出...使用java编程的完美数字
这里是我的代码:
import java.util.Scanner;
public class PerfectNumbers {
public static boolean isPerfect(int a) {
int n = a;
int sum = 0;
boolean perfect;
while (n-- >1) {
if(a%n==0)
sum = sum + n;
}
if (sum == a) {
perfect = true;
} else {
perfect = false;
}
return perfect;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the number up to which you would like to look for perfect numbers:");
int i = input.nextInt();
String factors = "";
System.out.printf("Looking for perfect numbers from 1 to %d%n", i);
while (i > 0) {
if (PerfectNumbers.isPerfect(i) == true) {
int w = i-1;
while (w-- > 1) {
if(i % w == 0)
factors = factors + " " + Integer.toString(w);
}
System.out.println(i + " is a perfect number it's factors are:" + factors);
}
i = i - 1;
}
}
}
但我希望它显示这个代替
您必须在每个完美数字后重置'因数'为空字符串 – Steve
我将如何“重置”因数?这是否意味着将它等同于一个空字符串?我是初学者,所以我还不确定 – cossii
而不是'while(i> 0)',添加'int j = 1;'并将条件改为'while(j <= i)'。还要把'i = i - 1;'改成'j = j + 1;'。这将解决排序问题。 – Gendarme