错误说它被零除而没有初始化为零

Error says it's dividing by zero while it's not initialised as zero

我正在尝试查找数字是否自守,代码编译正常但它说在我标记它的行上有被零除

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

解决此问题的方法可能是将除数设置为双精度或浮点数而不是整数

最初除数是 10。然后循环使除数乘以 10 一百次,得到 10101。这会多次溢出 int 范围,因为 231 大约是 2*1030.

特别是101000 = 2100*5100,所以循环32次后,每次乘以2,divisor的所有位都为零。

如果溢出 divisor 变为 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.");
    }
}