chap09/kadai3.f90

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

  1module mod_vector
  2  implicit none
  3  private
  4
  5  type :: vector2
  6    real(8) :: x, y
  7  endtype vector2
  8
  9  interface operator(+)
 10    module procedure add2
 11  endinterface operator(+)
 12
 13  interface operator(-)
 14    module procedure sub2
 15  endinterface operator(-)
 16
 17  interface operator(*)
 18    module procedure cross2
 19  endinterface operator(*)
 20
 21  interface assignment(=)
 22    module procedure assign2, assign2_array
 23  endinterface assignment(=)
 24
 25  interface show
 26    module procedure show2
 27  endinterface show
 28
 29  public :: vector2
 30  public :: show, operator(+), operator(-), operator(*), assignment(=)
 31
 32contains
 33
 34  !
 35  ! 2次元ベクトル用演算子
 36  !
 37  function add2(a, b) result(ret)
 38    implicit none
 39    type(vector2), intent(in) :: a, b
 40    type(vector2) :: ret
 41
 42    ret % x = a % x + b % x
 43    ret % y = a % y + b % y
 44  endfunction add2
 45
 46  function sub2(a, b) result(ret)
 47    implicit none
 48    type(vector2), intent(in) :: a, b
 49    type(vector2) :: ret
 50
 51    ret % x = a % x - b % x
 52    ret % y = a % y - b % y
 53  endfunction sub2
 54
 55  function cross2(a, b) result(ret)
 56    implicit none
 57    type(vector2), intent(in) :: a, b
 58    real(8) :: ret
 59
 60    ret = a % x * b % y - a % y * b % x
 61  endfunction cross2
 62
 63  subroutine assign2(a, b)
 64    implicit none
 65    type(vector2), intent(out) :: a
 66    real(8), intent(in) :: b
 67
 68    a % x = b
 69    a % y = b
 70  endsubroutine assign2
 71
 72  subroutine assign2_array(a, b)
 73    implicit none
 74    type(vector2), intent(out) :: a
 75    real(8), intent(in) :: b(2)
 76
 77    a % x = b(1)
 78    a % y = b(2)
 79  endsubroutine assign2_array
 80
 81  subroutine show2(v)
 82    implicit none
 83    type(vector2), intent(in) :: v
 84
 85    write(*, '("vector2 : ", f10.4, ",", f10.4)') v % x, v % y
 86    return
 87  endsubroutine show2
 88
 89endmodule mod_vector
 90
 91program answer
 92  use mod_vector
 93  implicit none
 94
 95  type(vector2) :: a, b, c
 96
 97  write(*, fmt='(a)') '--- vector2 ---'
 98
 99  a = (/1.0_8, 0.0_8/)
100  b = 1.0_8
101  c = a + b
102
103  call show(a + b)
104  call show(a - b)
105
106  stop
107endprogram answer