chap09/sample3.f90

サンプルコードのダウンロード

 1! 面積を計算するモジュール
 2module mod_area
 3  implicit none
 4
 5  real(8), parameter :: pi = 4 * atan(1.0_8)
 6
 7  ! 総称名を定義
 8  interface triangle
 9    module procedure triangle1, triangle2
10  endinterface triangle
11
12contains
13
14  ! 底辺と高さが与えられた時の面積の計算
15  function triangle1(a, b) result(area)
16    real(8), intent(in) :: a, b
17    real(8) :: area
18
19    area = a * b / 2
20
21  endfunction triangle1
22
23  ! 3つの頂点の座標が与えられた時の面積の計算
24  function triangle2(x1, y1, x2, y2, x3, y3) result(area)
25    real(8), intent(in) :: x1, y1, x2, y2, x3, y3
26    real(8) :: area
27
28    area = abs((x2 - x1) * (y3 - y1) - (x3 - x1) * (y2 - y1)) / 2
29
30  endfunction triangle2
31
32endmodule mod_area
33
34! メインプログラム
35program sample
36  use mod_area
37  implicit none
38
39  real(8) :: x1, y1, x2, y2, x3, y3, a, b
40
41  write(*, fmt='(a)', advance='no') 'Input height and base of tirangle : '
42  read(*, *) a, b
43
44  write(*, *) 'area of triangle = ', triangle(a, b)
45
46  write(*, fmt='(a)', advance='no') 'Input three apexes of triangle : '
47  read(*, *) x1, y1, x2, y2, x3, y3
48
49  write(*, *) 'area of triangle = ', triangle(x1, y1, x2, y2, x3, y3)
50
51  stop
52endprogram sample