Versions Compared
compared with
Key
- This line was added.
- This line was removed.
- Formatting was changed.
This example is meant as a helpfull guide to see how Fortran looks in practice. And will show how to use subroutines, precision and simple arithmetic functions in fortran.
Code Block | ||||
---|---|---|---|---|
| ||||
program main implicit none call menu() end program main |
Info |
---|
The line 'implicit none' is needed in Fortran to avoid obscure errors when defining variables. In earlier Fortran versions all variables were implicitly given as floats (real) unless the first letter in the name between i and n. 'implicit none' makes sure all variables have to be given-type explicit |
Code Block | ||||||||
---|---|---|---|---|---|---|---|---|
| ||||||||
recursive subroutine menu() !'recursive' is needed if the subroutine or function will call itself either directly or implicit integer :: choice logical :: valid !A boolean to indicate if the input is valid (.TRUE. or .FALSE.) print *, '--------------------' print *, '-----Calculator-----' print *, '--------------------' print *, 'Addition 1' print *, 'Subtraction 2' print *, 'Multiplication 3' print *, 'Division 4' print *, 'High precision division 5' print *, 'Power 6' print *, 'Terminate 0' valid = .FALSE. !Make shure the while loop runs atleast once do while (.NOT.valid) read *, choice valid = .TRUE. if (choice == 1) then call addition() else if (choice == 4) then call division() else if (choice == 5) then call hp_division() else if (choice == 6) then call power() else if (choice == 0) then print *, 'Program finished' else print *, 'False input, please enter valid input: ' valid = .FALSE. end if end do end subroutine menu |
The subroutine for addition:
Code Block | ||||||||
---|---|---|---|---|---|---|---|---|
| ||||||||
recursive subroutine addition()
implicit none
real :: a,b
print *, 'Enter two numbers to add'
read *, a,b
print *, 'Result: ', a+b
call menu()
end subroutine addition |
Code Block | ||||||||
---|---|---|---|---|---|---|---|---|
| ||||||||
recursive subroutine division()
implicit none
real :: a,b,res
print *, 'Enter two numbers to divide'
read *, a,b
res = a/b
print *, 'Result: ', res
call menu()
end subroutine division |
Code Block | ||||||||
---|---|---|---|---|---|---|---|---|
| ||||||||
recursive subroutine hp_division()
implicit none
integer, parameter :: ikind=selected_real_kind(p=12)
real(kind=ikind) :: a,b,res
print *, 'Enter two numbers to divide'
read *, a,b
res = a/b
print *, 'Result: ', res
call menu()
end subroutine hp_division
|
Code Block | ||||||||
---|---|---|---|---|---|---|---|---|
| ||||||||
recursive subroutine power()
implicit none
real :: base, pow
print *, 'Enter base then power'
read *, base, pow
print *, 'Result: ', base**pow
call menu()
end subroutine power
|
Panel | ||||||||
---|---|---|---|---|---|---|---|---|
| ||||||||
|
BibTeX Display Table |
---|