不打印完美的数字

时间:2015-07-24 08:05:09

标签: java 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 + " ");
        }
    }
}

为什么程序不能打印完美的数字?

我已经多次检查过代码,但我无法找到解决方案。请告诉我我的代码出了什么问题。谢谢提前

任何帮助都将不胜感激....

1 个答案:

答案 0 :(得分:2)

在这里,我查看了完美的数字生成并为您修复了它!

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变量,所以它们会为每个数字重置!