我试图找出该数字是否是自同构的,代码编译正常,但它说我标记它的行上有被零除
import java.util.Scanner;
class AutoLoop
{
public static void main()
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number to check if it's automorphic or not");
int num = sc.nextInt();
int sqr = num*num;
int sqrSave=sqr;
int divisor = 10;
int counter = 1;
while (counter<=100)
{
sqr = sqr%divisor; //It says there is divide by zero error on this line
if (sqr==num)
{
System.out.println("Number is an automorphic number");
break;
}
sqr=sqrSave;
divisor*=10;
counter++;
if (counter == 100)
System.out.println("Number is not an automorphic number till the 100th digit.");
}
}
}
我已经尝试过将其设置为 sqr%=divisor;还是不行。
最佳答案
我已经测试了你的代码,似乎你尝试将除数变量相乘超过 32 位整数限制,由于这是不可能的,它变成了一些其他数字,过了一会儿它变成了零。每次输入非自同构数时都会发生这种情况
这是每次代码循环时除数的值:
10
100
1000
10000
100000
1000000
10000000
100000000
1000000000
1410065408
1215752192
-727379968
1316134912
276447232
-1530494976
1874919424
1569325056
-1486618624
-1981284352
1661992960
-559939584
-1304428544
-159383552
-1593835520
1241513984
-469762048
-402653184
268435456
-1610612736
1073741824
-2147483648
0
解决此问题的方法可能是将除数设置为 double 或 float ,而不是整数
关于java - 错误表示它除以零,但未初始化为零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58605132/