英文:
How does this add up?
问题
Sure, here is the translated code:
public class Main{
    public static void main(String args[]){
        char a='3';
        int b=011;
        System.out.println(a+b);
    }
}
The answer turns out to be 60 but I don't understand how.
Could anyone please explain.
Thanks in advance :)
英文:
<!-- language: lang-java -->
public class Main{
public static void main(String args[]){
char a='3';
int b=011;
System.out.println(a+b);
}
}
The answer turns out to be 60 but I don't understand how.
Could anyone please explain.
Thanks in advance ![]()
答案1
得分: 3
首先,char + int 等于 int。因此,你将 char '3' 扩展为 int 51。其次,具有前导 0 的数字是八进制表示法。因此,011 是表示十进制 9 的另一种方式。51 + 9 = 60,或者
System.out.printf("%d + %d = %d%n", (int) a, b, a + b);
英文:
First, char + int is an int. So you're widening the char '3' to int 51. Second, numbers with a leading 0 are in octal. So 011 is another way to write decimal 9. 51 + 9 = 60, or
System.out.printf("%d + %d = %d%n", (int) a, b, a + b);
答案2
得分: 0
欢迎来到Stack Overflow!祝您旅途愉快!
当您将一个char和一个int相加时,结果将会是一个int。在这种情况下,char会被解释为其ASCII值,因此'3'对应的ASCII值是51。而011是一个八进制数,所以会被解释为1 * 8 + 1 = 9。因此,51 + 9 = 60。
英文:
welcome to stack overflow! Hope a good trip!
when you add a char and an int, it will output an int. In the situation, the char will be explained into its ASCII<https://www.ascii-code.com/> value, so '3' is 51. 011 is an octal number so it will be explained as 1 * 8 + 1 = 9. So, 51+9 = 60.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论