次のようなコードを確認しています。
float x = 9;
float y = 5;
int z = (int)(x / y);
質問:
z が int であると既に宣言されているのに、なぜ 3 行目に 2 番目の int があるのか疑問に思っています。前もって感謝します。
次のようなコードを確認しています。
float x = 9;
float y = 5;
int z = (int)(x / y);
質問:
z が int であると既に宣言されているのに、なぜ 3 行目に 2 番目の int があるのか疑問に思っています。前もって感謝します。
そう(x/y)
しないと、変数int
の値を で設定しようとして、コンパイラ エラーが発生します。この意図的な宣言は、数値の精度または範囲を縮小する場合に必要です。int
float
コンパイラによると、私たちは子供です..したがって、彼(コンパイラ)は、私たちがやっていることは意図的であり、間違いではないことを明示的に言及することを望んでいるため、明示的に指定する必要があります..
これらは 2 つのシナリオです: 1) With (int):
**Program:**
class fox
{
public static void main(String args[])
{
float x = 9;
float y = 5;
int z = (int)(x / y);
System.out.print(z);
}
}
**Output:**
# 1: hide clone input 8 seconds ago
result: success time: 0.07s memory: 380224 kB returned value: 0
input: no
output:
1
2) (int) なし:
**Program:**
class fox
{
public static void main(String args[])
{
float x = 9;
float y = 5;
int z = (x / y);
System.out.print(z);
}
}
**Output:**
Main.java:7: error: possible loss of precision
int z = (x / y);
^
required: int
found: float
1 error
# 1: hide clone 6 seconds ago
result: compilation error
// see the compiler cannot understand that we wish to do it purposefully,,