【问题标题】:what does [num[0]-'0'] mean and how to find the true number in System.out.println(onedigit[num[0]-'0']);[num[0]-\'0\'] 是什么意思以及如何在 System.out.println(onedigit[num[0]-\'0\']); 中找到真实数字
【发布时间】:2023-01-22 19:19:31
【问题描述】:

这是代码:

公共课 NumberToWord {

static void numberToWords(char num[]) {
    //determine the number's digits
    int len = num.length;
    //check the given number has number or not
    if (len == 0) {
        System.out.println("the string is empty");
    }
    //here we determine the limit of what should be the amount of digits to calculate
    //the number must be less than 4

    if (len > 4) {
        System.out.println("The given number has more than 4 digits");
    }

//one digit

String[] oneDigitNumbers = new String[]{"零", "一", "二", "三", "四", "五", "六", "七", "八", "九"} ;**

    String[] twoDigitNumbers = new String[]{"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
    String[] multipleOfTens = new String[]{"", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
    String[] powerOfTens = new String[]{"Hundred", "Thousand"};

    System.out.print("Conversion of the digit "+String.valueOf(num)+" to word is: ");

    if (len==1){
        System.out.println(oneDigitNumbers[num[0]-'0']);
       
    }
}


public static void main(String[] args) {
    numberToWords("2".toCharArray());
}

}

我不知道这段代码是如何工作的。

【问题讨论】:

  • 提示:char只是存储代表的数字指数分配给 Unicode 表中的字符/符号。例如字符A 有索引65(参见unicode-table.com/en/0041 - 0041 是十六进制数,十进制表示 4*16+1*1 = 64+1 = 65)。 B 字符的索引为 66。当我们减去 chars 时,我们正在研究他们的数值表示(索引)。所以当你写'B'-'A'时,它被计算为66-65,结果是1(所以这就像计算字符之间的距离)。同样适用于代表数字的字符'0' '1'..'9'

标签: java


【解决方案1】:

当你减去两个字符时,Java 会减去它们的 ASCII 值,'0' 的 ASCII 值是 48,而 1-9 紧随其后,所以当你从 '5' (53 - 48) 中减去一个 '0' 时,它会返回ASCII 差异等于您的字符的数字形式。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-20
    • 2023-03-28
    • 2020-04-02
    • 2018-09-10
    • 2016-06-03
    • 2014-11-06
    • 2017-10-29
    相关资源
    最近更新 更多