Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ Javaにおける数学演算 | 基本型と演算
/
Java基礎
セクション 2.  3
single

single

bookJavaにおける数学演算

メニューを表示するにはスワイプしてください

演算子

基本的な数学演算子 +-/* を使用していることがわかります。これらの演算子は電卓や数学でおなじみのものであり、コードエディタでも利用できます。

基本事項は以下の通りです:

  • + – 加算
  • - – 減算
  • / – 除算
  • * – 乗算

これら4つの基本演算子は、数値データ型(byteshortlongfloatdouble)で使用可能です。

これらの演算子の使用例をコードで確認します:

Main.java

Main.java

copy
1234567891011121314
package 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 には 1017 の合計である 27 が格納されています。

さらにいくつかの例を見てみましょう。

Main.java

Main.java

copy
12345678910111213141516171819
package 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

main.java

copy
12345678
package com.example; public class Main { public static void main(String[] args) { int result = (10 + 5) * 2 - 8 / 4 + 1; System.out.println(result); } }

ここでは、演算を順番に実行することで結果に到達しました。順序を見てみましょう。

したがって、算術と同様に通常の括弧を使って演算の実行順序を優先できます。

タスク

スワイプしてコーディングを開始

  1. 変数 firstNumbersecondNumber の値を加算します。
  2. 合計変数 thirdNumber の値で割ります。
  3. 最終結果を変数 result に格納します。

解答

Switch to desktop実践的な練習のためにデスクトップに切り替える下記のオプションのいずれかを利用して、現在の場所から続行する
すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 2.  3
single

single

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

some-alt