我试图查找数字是否是自同构的,代码可以很好地编译,但是它说我在上面标记的那行被零除
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;仍然不起作用。
答案 0 :(得分:2)
我已经测试了您的代码,似乎是您尝试将除数变量乘以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而不是整数
答案 1 :(得分:1)
最初的除数是10。然后循环使除数乘以100的奇数乘以10,得到10 101 。这会使int范围几次溢出,因为2 31 大约是2 * 10 30 。
尤其是10 1000 = 2 100 * 5 100 ,因此在循环32次后,每次乘以2, divisor
为零。
如果溢出divisor
变为0,则会得到除以零的错误。模%
的含义是抽象内部的除法(模除以余数)。
答案 2 :(得分:0)
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;
/* try with 10 and see the result. 100 is too big*/
while (counter<=100){
sqr = sqr%divisor;
if (sqr==num){
System.out.println("Number is an automorphic number");
break;
}
sqr=sqrSave;
divisor*=10;
counter++;
// try with 10 or an other number smaller than 100
if (counter == 100)System.out.println("Number is not an automorphic number till the 100th digit.");
}
}