1
1

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.

入力した値から四角形・三角形の面積を求める

Last updated at Posted at 2014-12-05

こんにちは、@Solphaです。

今回は、Goで三角形と四角形の面積を求めるプログラムを書いてみたいと思います。

概要

底辺と高さを入力し、入力された値を元に四角形と三角形の面積を求める。

四角形 = 底辺 × 高さ
三角形 = 底辺 × 高さ ÷ 2

プログラム

コード

square.go
package main

import "fmt"

func main() {
	var width, height, square, triangle int

	fmt.Printf("底辺の長さ(整数)を入力してください --> ")
	fmt.Scanln(&width)

	fmt.Printf("高さ(整数)を入力してください --> ")
	fmt.Scanln(&height)

	square = width * height
	triangle = width * height / 2

	fmt.Println("四角形の面積=", square)
	fmt.Println("三角形の面積=", triangle)
}

色んなサイトとかgolang.jpを見ていたら、fmtパッケージのスキャン(Scanなど)で値が入力できることを知ったので、さっそく使ってみました。こうすることで、底辺と高さを入力することができます。

fmt.Scanln(&width)の中で書かれている & は「アドレス演算子」と呼ばれるもので、「ポインタ」を理解するために避けては通れないようですが、参考書を読んでもサッパリだったので今回は断念・・・。

実行結果

$ go run square.go
底辺の長さ(整数)を入力してください --> 4
高さ(整数)を入力してください --> 2
四角形の面積= 8
三角形の面積= 4

所感

値の入力ができるようになれば、少し幅が広がりそうですね。

次は整数以外の値を扱うプログラムなんかを書いてみたいと思います。

1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?