gpt4 book ai didi

java - java循环中的计数器和累加器

转载 作者:行者123 更新时间:2023-11-30 06:24:57 24 4
gpt4 key购买 nike

我正在做这个程序:给定一个整数n,如果它的除数之和(不计算本身)等于n,则该数字被认为是完美的。如果金额较少,则称为不足;如果金额较多,则称为丰富。例如:

6 有约数 1,2,3:它们加 6,因此 6 是完美的。 8 有约数 1,2,4:它们加 7,因此 8 是 deciente。 24 有约数 1,2,3,4,6,8,12:它们加上 36,因此 24 是丰富的。

编写一个程序,读取两个正整数,并在屏幕上显示该区间内每种类型的数字数量(包括极值)。

我有以下代码,我知道它在哪里失败,例如,如果我输入一个数字,我会做得很好,例如条目 6 和 7。如果我输入 6 和 9,则输出是 Perfect 1 Deficient 0丰富 2,当我应该完美 1 不足 2 丰富 0 时。变量 j 将所有的除数存储在变量 j 中,这就是为什么它是丰富的,但我无法比我尝试过的更正它。

import java.util.Scanner;

public class PerfectNumbers {

public static void main(String[] args) {

System.out.println("Enter two numbers for the interval:");
Scanner teclado = new Scanner(System.in);
int x = teclado.nextInt();
int y = teclado.nextInt();

int cont1 = 0;
int perfect = 0;
int deficient = 0;
int abundant = 0;

for (int i = x; i < y; i++) {
for (int j = 1; j < i; j++) {

if (i % j == 0) {

cont1 += j;
} else {
cont1 += 0;
}

}
if (cont1 == x) {
perfect += 1;
} else if (cont1 < x) {
deficient += 1;
} else if (cont1 > x) {
abundant += 1;
}
}

System.out.println("Perfect"+ perfect);
System.out.println("Deficient"+ deficient);
System.out.println("Abundant"+ abundant);
}
}

最佳答案

一个问题是您没有重置 cont1

另一个问题是,您需要与 i 进行比较,而不是与 x 进行比较来决定完美/不足/丰富。

for (int i = x; i < y; i++) {
cont1 = 0;
for (int j = 1; j < i; j++) {
if (i % j == 0) {
cont1 += j;
}
}

if (cont1 == i) {
perfect += 1;
} else if (cont1 < i) {
deficient += 1;
} else {
abundant += 1;
}
}

我认为第二个问题很容易被忽视,因为变量的命名很糟糕。我建议改进这一点,这样会更容易阅读,也更难犯这样的错误:

for (int n = start; n < end; n++) {
sum = 0;
for (int j = 1; j < n; j++) {
if (n % j == 0) {
sum += j;
}
}

if (sum == n) {
perfect++;
} else if (sum < n) {
deficient++;
} else {
abundant++;
}
}

关于java - java循环中的计数器和累加器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47366122/

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