Last active
November 25, 2018 05:07
-
-
Save komasaru/ec30b23db60226d89bec58b5a5daddb0 to your computer and use it in GitHub Desktop.
Fortran 95 source code to compute with Reverse Polish Notation method.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
!**************************************************** | |
! 逆ポーランド記法 (Stack モジュール使用) | |
! | |
! date name version | |
! 2018.08.21 mk-mode.com 1.00 新規作成 | |
! | |
! Copyright(C) 2018 mk-mode.com All Rights Reserved. | |
!**************************************************** | |
! | |
program main | |
use stack | |
implicit none | |
character(len=80) :: buf | |
integer :: i | |
print '(A)', "Calculator by Reverse Polish Notation." | |
do | |
read (*,'(A80)') buf | |
if (len(trim(buf)) == 0) exit | |
do i = 1, len(trim(buf)) | |
select case (buf(i:i)) | |
case (" ") | |
cycle | |
case ("0":"9") | |
call push(ichar(buf(i:i)) - ichar('0')) | |
case ("+") | |
call push(pop() + pop()) | |
case ("-") | |
call push(- pop() + pop()) | |
case ("*") | |
call push(pop() * pop()) | |
case ("=") | |
exit | |
case default | |
print *, "Unknown operator." | |
exit | |
end select | |
enddo | |
print '(A,I15)', "Ans: ", pop() | |
enddo | |
stop | |
end program main |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
!**************************************************** | |
! Stack モジュール | |
! | |
! date name version | |
! 2018.08.21 mk-mode.com 1.00 新規作成 | |
! | |
! Copyright(C) 2018 mk-mode.com All Rights Reserved. | |
!**************************************************** | |
! | |
module stack | |
implicit none | |
private ! デフォルトを private に設定 | |
public :: pop, push ! pop, push のみ public とする | |
! 以下の変数は private となる。 | |
integer, parameter :: pmax = 256 ! スタックの最大長 | |
integer, save :: buf(1:pmax) ! スタック配列 | |
integer, save :: p = 0 ! 最後(トップ)の要素の位置 | |
contains | |
! Pop from a stack | |
! : スタックからトップノードを取り出す | |
integer function pop() | |
implicit none | |
if (p > 0) then | |
pop = buf(p) ! 最後の要素を取り出す | |
p = p - 1 ! 最後の要素の位置を左に 1 つずらす | |
else | |
print *, "Stack underflow!" | |
pop = - huge(p) | |
end if | |
return | |
end function pop | |
! Push into a stack | |
! : スタックに n をトップノードとして付け加える | |
! | |
! :param integer n | |
subroutine push(n) | |
implicit none | |
integer, intent(IN) :: n | |
if (p < pmax) then | |
p = p + 1 ! 最後の要素の位置を右に 1 つずらす | |
buf(p) = n ! 要素を付け加える | |
else | |
print * "Stack overflow!" | |
end if | |
return | |
end subroutine push | |
end module stack |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment