我试图为一系列数字创建一个完美的数字测试,其中n是起始编号,endNum是结束编号。它不会正常循环,但是完美的数字测试("而#34;循环中的部分)单独工作。我做错了什么?
import java.util.Arrays;
import java.util.Scanner;
public class CodingChallenge3 {
public static void main(String[] args) {
int n, sum = 0;
Scanner s = new Scanner(System.in);
System.out.print("Welcome to the Perfect Number Tester."
+ "\n" + "Enter a number range."
+ "\n" + "From: ");
n = s.nextInt();
System.out.print("To: ");
int endNum = s.nextInt();
while (n <= endNum) {
for (int i = 1; i < n; i++) {
if (n % i == 0) {
sum = sum + i;
}
}
if (sum == n && n != 0) {
System.out.println(n + " is perfect");
}
if (sum > n) {
System.out.println(n + " is imperfect abundant");
}
if (sum < n) {
System.out.println(n + " is imperfect deficient");
}
if (n == 0) {
System.out.println(n + " has no factors");
}
n++;
}
}
}
答案 0 :(得分:4)
您忘记重置n
的每个值的总和:
while (n <= endNum) {
sum = 0; // add this
for (int i = 1; i < n; i++) {
if (n % i == 0) {
sum = sum + i;
}
}
if (sum == n && n != 0) {
System.out.println(n + " is perfect");
}
if (sum > n) {
System.out.println(n + " is imperfect abundant");
}
if (sum < n) {
System.out.println(n + " is imperfect deficient");
}
if (n == 0) {
System.out.println(n + " has no factors");
}
n++;
}