17
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Go: int同士の割り算は、intが戻り値なので注意

Last updated at Posted at 2015-05-18

整数同士の割り算、例えば 100000 ÷ 30 = 3333.333333333 の結果はfloatになりそうですが、Goは3333のようにintが戻り値になるので注意が必要です。

計算結果を少数として欲しい時は、計算に使う数字をfloat64に変換しておく必要があります。

play.golang.org/p/iq539h6DGI
package main

import (
	"fmt"
)

func main() {
	fmt.Printf("%t\n", 10 / 3) // 3
	fmt.Printf("%t\n", 10 / 3.0) // %!t(float64=3.3333333333333335)
	fmt.Printf("%t\n", 10.0 / 3) // %!t(float64=3.3333333333333335)
	fmt.Printf("%t\n", float64(10) / 3) // %!t(float64=3.3333333333333335)
	fmt.Printf("%t\n", 10 / float64(3)) // %!t(float64=3.3333333333333335)
	
	if 10 / 3 > 3 {
		fmt.Println("10 / 3 > 3 = TRUE")
	} else {
		fmt.Println("10 / 3 > 3 = FALSE")
	}
	
	if 10 / 3 > float64(3) {
		fmt.Println("10 / 3 > float64(3) = TRUE")
	} else {
		fmt.Println("10 / 3 > float64(3) = FALSE")
	}
	
	if 10 / float64(3) > 3 {
		fmt.Println("10 / float64(3) > 3 = TRUE")
	} else {
		fmt.Println("10 / float64(3) > 3 = FALSE")
	}
}

このコードを実行してみる

17
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
17
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?