セクション 2. 章 3
single
Javaにおける数学演算
メニューを表示するにはスワイプしてください
演算子
基本的な数学演算子 +、-、/、* を使用していることがわかります。これらの演算子は電卓や数学でおなじみのものであり、コードエディタでも利用できます。
基本事項は以下の通りです:
+– 加算-– 減算/– 除算*– 乗算
これら4つの基本演算子は、数値データ型(byte、short、long、float、double)で使用可能です。
これらの演算子の使用例をコードで確認します:
Main.java
1234567891011121314package com.example; public class Main { public static void main(String[] args) { // Creating an int variable with value 10 int a = 10; // Creating an int variable with value 17 int b = 17; // Creating an int variable to store the sum of `a` and `b` int res = a + b; // Printing the result to the console System.out.println(res); } }
ご覧のとおり、変数 res には 10 と 17 の合計である 27 が格納されています。
さらにいくつかの例を見てみましょう。
Main.java
12345678910111213141516171819package com.example; public class Main { public static void main(String[] args) { // Creating an int variable with the sum of 16 and 4 int plus = 16 + 4; /* Creating an int variable with the value of the subtraction of the `plus` variable and 10 */ int minus = plus - 10; /* Variable that holds the result of multiplying the `minus` variable by 4 */ int multiplying = minus * 4; /* Using subtraction and division operations on the `multiplying` variable */ int complexDivision = (multiplying - 4) / 9; // Printing the result to the console System.out.println(complexDivision); } }
演算では数値と変数の両方を使用可能ですが、多くの変数を作成するとスタックメモリの使用量が増加するため、数値を直接使用する方が望ましい場合が多いです。演算子の優先順位が適用されます:まず括弧、次に乗算や除算、最後に加算や減算です。
これにより、異なる数値を使った簡単な演算が可能となります。
演算の順序
Javaは数学の基本原則に従い、演算にも実行順序があります。例を見てみましょう:
main.java
12345678package com.example; public class Main { public static void main(String[] args) { int result = (10 + 5) * 2 - 8 / 4 + 1; System.out.println(result); } }
ここでは、演算を順番に実行することで結果に到達しました。順序を見てみましょう。
したがって、算術と同様に通常の括弧を使って演算の実行順序を優先できます。
タスク
スワイプしてコーディングを開始
- 変数
firstNumberとsecondNumberの値を加算します。 - 合計を変数
thirdNumberの値で割ります。 - 最終結果を変数
resultに格納します。
解答
すべて明確でしたか?
フィードバックありがとうございます!
セクション 2. 章 3
single
AIに質問する
AIに質問する
何でも質問するか、提案された質問の1つを試してチャットを始めてください