自动将浮点数转换为整数。 – Java

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

Auto Conversion of floating point number to int. - Java

问题

当我在编写程序时忘记写Math.round(),当我回顾代码时,我看到了这个代码:

int number = 1/2;

为什么这不会引发一个错误,显示为required type: int | provided: double

注意:如果这是一个愚蠢的问题,请原谅,我是编程新手。

英文:

I was writing a program and forgot to write Math.round() and when I was reviewing the code I saw this

int number = 1/2;

why doesn't this raise an error of
required type: int | provided:double?

Note: If this is a silly question please forgive I new to programming.

答案1

得分: 1

这是一种自动类型转换。在这里,变量'number'存储了自动转换为整数0的值。

然而,自动类型转换并不总是有效。当你写int number = 0.5;时会出现错误,但是当你写int number = (int) 0.5;时,这被称为显式类型转换,此时number存储0的值。

英文:

its an automatic type conversion.

Here the variable 'number' stores the auto converted value to int 0.

well auto type casting doesn't always work.
when you write int number = 0.5; it will give an error

but when you write int number = (int) 0.5; its called an explicit type casting and now number stores 0 value.

答案2

得分: 1

Sure, here's the translated content:

通常使用 double 进行数学运算的话,很可能会得到 double 的结果;而对于整数,则会得到一个 int 的结果。

然而,如果情况不是这样的话,Java 会截断小数点后面的数字,并将值设置为剩下的部分。例如:

3/4 = 1.5 => Java => 1
英文:

Normally doing math operations using double will most likely be giving double on the other hand for int it will give a int.

However, if thats not the case Java will strip the number after the dot (.) and set the value to whatever is left. Example:

3/4 = 1.5 => Java => 1

huangapple
  • 本文由 发表于 2020年8月12日 12:40:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/63369865.html
匿名

发表评论

匿名网友

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

确定