英文:
Widening and Narrowing of Primitive Types question
问题
我是一名一年级的计算机科学专业学生。我们刚开始学习 Java 编程语言。我们的教授向我们讲解了类型扩展,但有一点我不太明白,也许你可以帮助我解答一下。当你进行以下运算:(double * int) + (char / short) – (float * byte),答案会是 double 类型。但是,老师还告诉我们,针对 (char / short) 的计算结果会是 float 类型。为什么会是 float 呢?
谢谢!
英文:
I am a first year computer science student. We just starded learning java.
Our prof told us about the widening, but i did not understand something and maybe you can help me.
When you do the following operation (double*int) + (char /-short ) – (float * byte) the answer will be double. But, the teacher also told us that the answer just for (char /-short ) will be float. Why float?
Thanks!
答案1
得分: 2
你的老师是错误的。结果将是 int
类型的。
具体规则在Java语言规范的第5.6.2节中有详细说明,指出在执行除法之前,除法的两个操作数将会被扩展为 int
类型,因此结果将是 int
。
英文:
Your teacher is wrong. The result will be of type int
.
The exact rules are outlined in the Java Language Specification section 5.6.2, which indicates that both operands of the division will be widened to type int
before the division takes place, so the result will be an int
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论