Go の基礎

Go Operators and Arithmetic

Why is 17 / 5 equal to 3 in Go? Learn arithmetic, comparison and logical operators.

  • 初級
  • 約3分で読めます
  • 実行できるサンプル 1 件
学べること
  • + - * / and %
  • Integer division
  • &&, || and ++
Expression → result
17 / 53
17 % 52
float64(17) / float64(5)3.4
math.Pow(2, 10)1024

How Go evaluates an expression

Operators combine values into expressions. Go follows the usual math rules, with one thing to remember: dividing two integers drops the fraction.

17 / 5 is 3 because both numbers are integers, and 17 % 5 is the remainder 2. Converting both sides to float64 keeps the fraction. && is true only when both comparisons are true. count++ adds one and is a statement, not an expression.

重要なポイント

  1. int / int drops the fraction: 17 / 5 is 3.
  2. % gives the remainder: 17 % 5 is 2.
  3. Convert to float64 to keep the fraction.

実行できる Go のサンプル

Go
コードを実行 →
main.go
package main

import (
	"fmt"
	"math"
)

func main() {
	a, b := 17, 5
	fmt.Println(a+b, a-b, a*b)
	fmt.Println(a/b, a%b)
	fmt.Println(float64(a) / float64(b))
	fmt.Println(a > b && b != 0)
	fmt.Println(math.Pow(2, 10), math.Sqrt(144))

	count := 0
	count++
	count += 10
	fmt.Println(count)
}
この例の実行ボタンを作成 実行結果
22 12 85
3 2
3.4
true
1024 12
11

練習

サンプルをオンラインコンパイラーで開き、値を変えたり行を追加したりして、実行する前に出力を予想してみましょう。次に、わざとコードを壊してコンパイラーのメッセージを読んでみてください。

このレッスンを終えましたか?

学習済みにすると進み具合を記録できます。

次へ: Reading User Input →

チャレンジで練習する

このレッスンの内容を使って実際の問題を解きましょう。各チャレンジはブラウザで動き、すぐにテストされ、AI のレビューも受けられます。

すべてのチャレンジ