簡體   English   中英

乘法變量時的錯誤答案

[英]Wrong answer when multiplying variables

我試圖將兩個變量相乘。 一個是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;

問題出在currProduct*= array[x]

打印出來時這是我的輸出:

1 * 7 = 55
55 * 3 = 2805
2805 * 1 = 137445
137445 * 6 = 7422030
7422030 * 7 = 408211650

為什么它不能正確倍增?

問題是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

因此,要編輯代碼,它將如下所示:

        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]);
            }

        }

輸出:

1 * 7 = 7
7 * 3 = 21
21 * 1 = 21
21 * 6 = 126
126 * 7 = 882

驗證: 7*3*1*6*7 = 882

試試這樣:

currProduct *= (int) array[x];

在這里為了什么char值通常代表。 你會看到如果你想讓你的char保持數值2,你必須實際分配50:

char two = 50;
System.out.println(two); // prints out 2

'7'的值是55,因為它只是另一個字符,例如'a',因此它的數值將是它的ASCII碼。 見這里: http//www.asciitable.com/
(請注意,使用的ASCII表也可以依賴於實現。)

'7'的數值不是7,它是55.這就像任何字符一樣,例如字符'A'是65

例如

public class Calendar
{
    public static void main(String[] args){
        char testChar='7';
        int testInt=testChar;

        System.out.println(testInt); //prints 55
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM