简体   繁体   中英

Why is my Beam number program giving the wrong output?

A Beam number is a number in which the sum of the squares of the digits of the number is larger than the number itself.

For example: In the no. 25, sum of the square of digits = 2^2 + 5^2 = 4 + 25 = 29 (greater than the number accepted)

Hence 25 is a Beam number.

Here is my code:

import java.util.Scanner;
class test
{
    public static void main()
    {
        System.out.println("\f");
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the number");
        int m = sc.nextInt(); 
        int sum  = 0;
        while (m > 0)
        {
            sum += (m%10)*(m%10);
            m = m/10;
        }
        if (sum > m)
        {
            System.out.println("It is a Beam number");
        }
        else
        {
            System.out.println("It is not a Beam number");
        }
    }
}

The program compiles properly, but there is some problem in the logic, as it doesn't give the desired output. A picture of the output is given: 在此处输入图像描述

51 is clearly not a Beam no. as the sum of the squares of its digits (25+1=26) is less than 51 itself. What changes do I make?

Your while loop is destroying the information about the inputted number. Whenever you enter a number greater than 0, the sum will be greater than 0, but m will always be 0 .

Use another variable, initialized to m , in the while loop to perform your calculations, so that m stays the inputted value, so that your comparison at the end is correct.

Here is how you might have debugged this yourself. Notice the print statements.

class test // unrelated note:  by convention class names should start with
           // upper case letters.
{
    public static void main()
    {
        System.out.println("\f");
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the number");
        int m = sc.nextInt(); 
        int sum  = 0;
        System.out.println("Before while loop.");
        System.out.println("m = " + m + ", sum = " + sum);
        while (m > 0)
        {
            sum += (m%10)*(m%10);
            m = m/10;
        }
        System.out.println("After while loop.");
        System.out.println("m = " + m + ", sum = " + sum);
        if (sum > m)
        {
            System.out.println("It is a Beam number");
        }
        else
        {
            System.out.println("It is not a Beam number");
        }
    }
}

Using print statements in key locations and printing out various fields is the first and most common step in debugging programs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM