gpt4 book ai didi

java - 无法在循环中嵌套完美数字测试

转载 作者:行者123 更新时间:2023-11-29 08:28:16 27 4
gpt4 key购买 nike

我正在尝试为一系列数字创建完美数字测试,n 是起始数字,endNum 是结束数字。它不会正确循环,但完全数字测试(“while”循环内的部分)会自行运行。我做错了什么?

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++;
}

}

最佳答案

您忘记为 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++;
}

关于java - 无法在循环中嵌套完美数字测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50585832/

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