双int转换混乱

时间:2013-06-23 22:55:30

标签: java casting type-conversion

当我尝试将2个int值相乘时,我不知道为什么这段代码会产生以下输出。这可能太愚蠢但我不明白。我在这里粘贴了代码和输出

public static void main(String[] args) {
    // TODO code application logic here
    String numstring = "12122";
    char[] numArray = numstring.toCharArray();
    int num =0;
    int index = 10;
    int count = 0;
    for(int i=numArray.length-1;i>=0;i--){
      int ind = (int)(Math.pow(index,count));
      System.out.print(numArray[i]+"*"+ind);
      System.out.println(" prints as ----->"+numArray[i]*ind);
      count++;
    }
}

输出:

    2*1 prints as ----->50
    2*10 prints as ----->500
    1*100 prints as ----->4900
    2*1000 prints as ----->50000
    1*10000 prints as ----->490000

2 个答案:

答案 0 :(得分:1)

你不会乘以两个整数。您将int ind char'2'相乘,其ASCII值为50(至少在第一种情况下)。您可以使用int[],或者如果您想坚持使用char[],则可以执行以下操作:

System.out.println(" prints as ----->"+ Character.getNumericValue(numArray[i]) * ind);

答案 1 :(得分:0)

字符实际上是整数,所以例如,字符'2'的值为50。

要查看哪个整数对应哪个字符,请查看ascii table

要做你想做的事,你应该使用Character.getNumericValue()方法:

System.out.println(" prints as ----->"+Character.getNumericValue(numArray[i])*ind);