不打印完美数字
Not printing perfect numbers
这是我的代码:-
package javaapplication;
import java.util.Scanner;
public class perfect02 {
public static void main(String args[]) {
int i = 1, sum = 0;
System.out.println("Enter maximum range : ");
Scanner kb = new Scanner(System.in);
int a = kb.nextInt();
System.out.println("Enter minimum range : ");
Scanner kb2 = new Scanner(System.in);
int b = kb2.nextInt();
System.out.println("perfect number in the given range are :");
for (int n = b; n <= a; n++) {
while (i < n) {
if (n % i == 0) {
sum = sum + i;
}
i++;
}
if (sum == n)
System.out.println(+n + " ");
}
}
}
为什么程序不打印完美数字?
我已经多次检查代码,但找不到解决方案。请告诉我我的代码出了什么问题。提前致谢
如有任何帮助,我们将不胜感激....
在这里,我研究了完美数字生成并为您修复了它!
public static void main(String args[]) {
Scanner kb = new Scanner(System.in);
System.out.println("Enter minimum range : ");
int b = kb.nextInt();
System.out.println("Enter maximum range : ");
int a = kb.nextInt();
kb.close();
System.out.println("Perfect number in the given range are :");
for (int n = b; n <= a; n++) {
int sum = 0;
int i = 1;
while (i < n) {
if (n % i == 0)
sum = sum + i;
i++;
}
if (sum == n)
System.out.println(n + " is perfect");
}
}
您应该在 for 循环内声明 sum 和 i 变量,这样它们会为每个数字重置!
这是我的代码:-
package javaapplication;
import java.util.Scanner;
public class perfect02 {
public static void main(String args[]) {
int i = 1, sum = 0;
System.out.println("Enter maximum range : ");
Scanner kb = new Scanner(System.in);
int a = kb.nextInt();
System.out.println("Enter minimum range : ");
Scanner kb2 = new Scanner(System.in);
int b = kb2.nextInt();
System.out.println("perfect number in the given range are :");
for (int n = b; n <= a; n++) {
while (i < n) {
if (n % i == 0) {
sum = sum + i;
}
i++;
}
if (sum == n)
System.out.println(+n + " ");
}
}
}
为什么程序不打印完美数字?
我已经多次检查代码,但找不到解决方案。请告诉我我的代码出了什么问题。提前致谢
如有任何帮助,我们将不胜感激....
在这里,我研究了完美数字生成并为您修复了它!
public static void main(String args[]) {
Scanner kb = new Scanner(System.in);
System.out.println("Enter minimum range : ");
int b = kb.nextInt();
System.out.println("Enter maximum range : ");
int a = kb.nextInt();
kb.close();
System.out.println("Perfect number in the given range are :");
for (int n = b; n <= a; n++) {
int sum = 0;
int i = 1;
while (i < n) {
if (n % i == 0)
sum = sum + i;
i++;
}
if (sum == n)
System.out.println(n + " is perfect");
}
}
您应该在 for 循环内声明 sum 和 i 变量,这样它们会为每个数字重置!