[英]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. Beam数是一个数字,其中数字的数字的平方和大于数字本身。
For example: In the no.例如:在没有。 25, sum of the square of digits = 2^2 + 5^2 = 4 + 25 = 29 (greater than the number accepted)
25,数字平方和 = 2^2 + 5^2 = 4 + 25 = 29(大于接受的数字)
Hence 25 is a Beam number.因此 25 是 Beam 编号。
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.程序编译正确,但逻辑上存在一些问题,因为它没有给出所需的 output。 A picture of the output is given:
给出一张output的图片:
51 is clearly not a Beam no. 51 显然不是 Beam 号。 as the sum of the squares of its digits (25+1=26) is less than 51 itself.
因为其数字的平方和 (25+1=26) 本身小于 51。 What changes do I make?
我要做哪些改变?
Your while loop is destroying the information about the inputted number.您的 while 循环正在破坏有关输入数字的信息。 Whenever you enter a number greater than 0, the sum will be greater than 0, but
m
will always be 0
.每当您输入大于 0 的数字时,总和将大于 0,但
m
将始终为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.在
while
循环中使用另一个初始化为m
的变量来执行计算,以便m
保持输入的值,以便最后的比较是正确的。
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.在关键位置使用
print statements
并打印出各个字段是调试程序的第一步也是最常见的步骤。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.