校验和计算器不获取最后一位

bvjxkvbb  于 2021-07-04  发布在  Java
关注(0)|答案(2)|浏览(281)

所以当我输入一个12位长的数字时,它会正确地计算校验和。但是如果我输入一个13位数的长数字,它就会出错。

public static void checksum(long l) {

    long x1   = l / 100000000000l % 10;
    long x2   = l / 10000000000l % 10;
    long x3   = l / 1000000000 % 10;
    long x4   = l / 100000000 % 10;
    long x5   = l / 10000000 % 10;
    long x6   = l / 1000000 % 10;
    long x7   = l / 100000 % 10;
    long x8   = l / 10000 % 10;
    long x9   = l / 1000 % 10;
    long x10  = l / 100 % 10; 
    long x11  = l / 10 % 10;
    long x12  = l / 1 % 10;
    long x13  = l  % 10;

   long calculation = x1+(x2*3)+x3+(x4*3)+x5+(x6*3)+x7+(x8*3)+x9+(x10*3)+x11+(x12*3)+x13;
    System.out.println(calculation);
}
smdnsysy

smdnsysy1#

这是你需要用到的。在最初的模块化计算中,你的误差是10倍。

checksum(3729483022008L);

public static void checksum(long l) {

        long x1   = l / 1000000000000L % 10;
        long x2   = l / 100000000000L % 10;
        long x3   = l / 10000000000L % 10;
        long x4   = l / 1000000000 % 10;
        long x5   = l / 100000000 % 10;
        long x6   = l / 10000000 % 10;
        long x7   = l / 1000000 % 10;
        long x8   = l / 100000 % 10;
        long x9   = l / 10000 % 10;
        long x10  = l / 1000 % 10; 
        long x11  = l / 100 % 10;
        long x12  = l / 10 % 10;
        long x13  = l / 1 % 10;

        long calculation = x1 + (x2 * 3) + x3 + (x4 * 3) + x5
                + (x6 * 3) + x7 + (x8 * 3) + x9 + (x10 * 3) + x11
                + (x12 * 3) + x13;

        System.out.println(calculation);
}

印刷品

100
fjnneemd

fjnneemd2#

这是正常的,因为 x1 你除以 10^11 ,然后你就申请了 %10 ,如果数字大于10^13(因此长度大于等于13),则不使用新数字

System.out.println(l / 100000000000L);      // 37
System.out.println(l / 100000000000L % 10); // 7

手术 number / ((long) Math.pow(10, i)) % 10 接受 i-th 数字 number ,所以12是最大的,你不会得到13或更大的
事实上,这个问题和你上次使用的问题是一样的 8 两次,你需要移动所有的因子,把它们乘以10

public static void checkSum(long l) {

    long x1 = l / 1000000000000L % 10;
    long x2 = l / 100000000000L % 10;
    long x3 = l / 10000000000L % 10;
    long x4 = l / 1000000000 % 10;
    long x5 = l / 100000000 % 10;
    long x6 = l / 10000000 % 10;
    long x7 = l / 1000000 % 10;
    long x8 = l / 100000 % 10;
    long x9 = l / 10000 % 10;
    long x10 = l / 1000 % 10;
    long x11 = l / 100 % 10;
    long x12 = l / 10 % 10;
    long x13 = l % 10;

    long calculation = x1 + (x2 * 3) + x3 + (x4 * 3) + x5 + (x6 * 3) + x7 + (x8 * 3) + x9 +
        (x10 * 3) + x11 + (x12 * 3) + x13;
    System.out.println(calculation);

}

相关问题