乘法变量时的错误答案

Mar*_*loe 2 java math

我试图将两个变量相乘.一个是int,另一个是char数组.

我的代码是这样的

int biggestProduct = 1;
int currProduct = 1;
char[] array = num.toCharArray();

for (int x = 0; x < array.length; x++) {
    if (x < 5) {
        System.out.println(currProduct + " * " + array[x] + " = " + currProduct * array[x]);
        currProduct *= array[x];
    }
}

return biggestProduct;
Run Code Online (Sandbox Code Playgroud)

问题在于 currProduct*= array[x]

打印出来时这是我的输出:

1 * 7 = 55
55 * 3 = 2805
2805 * 1 = 137445
137445 * 6 = 7422030
7422030 * 7 = 408211650
Run Code Online (Sandbox Code Playgroud)

为什么它不能正确倍增?

Ale*_* C. 8

问题是,的数值char 7不是7,但55.

因为在Java中,char数据类型是单个16位Unicode字符(请参阅下面的编码表).

在此输入图像描述

如果您查看此表,您会看到7被编码为0x0037 = 3*16^1 + 7 = 55.

如果要获取角色的实际数值,可以使用Character.getNumericValue(char ch):

 char ch = '7';
 int number = Character.getNumericValue(ch);
 System.out.print(number); //print 7
Run Code Online (Sandbox Code Playgroud)

因此,要编辑代码,它将如下所示:

        String num = "73167";
        int biggestProduct = 1;
        int currProduct = 1;
        char[] array = num.toCharArray();

        for (int x = 0; x < array.length; x++) {
            if (x < 5) {
                System.out.println(currProduct + " * " + array[x] + " = " + currProduct * Character.getNumericValue(array[x]));
                currProduct *= Character.getNumericValue(array[x]);
            }

        }
Run Code Online (Sandbox Code Playgroud)

输出:

1 * 7 = 7
7 * 3 = 21
21 * 1 = 21
21 * 6 = 126
126 * 7 = 882
Run Code Online (Sandbox Code Playgroud)

验证: 7*3*1*6*7 = 882