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