原始类型的扩宽和缩窄问题

huangapple go评论79阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2020年10月15日 03:11:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/64360051.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定