Fortran — один из старейших языков программирования, который используется до сих пор. С годами он потерял свой блеск и популярность, но по-прежнему остается удобным инструментом для ученых, инженеров и начинающих программистов. Это отличный язык для начинающих программистов, потому что он имеет строгие правила, такие как 72-символьные предельные строки, а также небольшую встроенную функциональность, которая требует большего осмысления и понимания процессов, но обеспечивает превосходную гибкость функциональности. В этой статье мы рассмотрим многочисленные примеры того, как Фортран можно применять для решения уникальных задач.
Фортран для разработки месторождений
! Programmer: Roberto Carlos Baldizon Diaz ! Program: Diff ! Description: This program solves 1-D Steady State ! Diffusivity using Central Difference !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! subroutine thomas(a,b,c,d,n) implicit none ! DATA DICTIONARY integer,intent(in) :: n real(4),dimension(n),intent(in) :: a,b,c,d real(4),dimension(n) :: x real (4) :: m real(4),dimension(n) :: c_k,d_k integer :: i ! PROCESS c_k(1)=c(1)/b(1) d_k(1)=d(1)/b(1) do i=2,n m = b(i)-c_k(i-1)*a(i) c_k(i) = c(i)/m d_k(i) = (d(i)-d_k(i-1)*a(i))/m end do x(n) = d_k(n) ! OUTPUT do i=n-1,1,-1 x(i)=d_k(i)-c_k(i)*x(i+1) end do do i = 1, n, 1 write(*,*) x(i) end do end subroutine thomas !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! program diff implicit none ! DATA DICTIONARY integer, parameter :: n=10 integer :: dx integer :: i real, parameter :: P_in=1000 real, parameter :: P_out=3000 real, dimension (n) :: l real, parameter :: x_2=2000 real, dimension (n) :: k0 real, dimension (n) :: k real, dimension(n) :: a real, dimension(n) :: b real, dimension(n) :: c real, dimension(n) :: d ! PROCESS i=0 dx=x_2/n do i = 1, n-1, 1 l(i) = dx/2 + i*dx end do do i= 1, n, 1 k0(i) = 100 *0.5*(2000-l(i)) end do k(n)=k0(n) do i = 1, n, 1 d(1) = — 2*k(1)*k(1+1)/(k(1)+k(1+1))*P_in if(i>1) then a(i) = 2*k(i)*k(i+1)/(k(i)+k(i+1)) b(i) = -( 2*k(i)*k(i+1)/(k(i)+k(i+1))+2*k(i+1)*k(i+2) + /(k(i+1)+k(i+2))) else if(i<n) then c(i) = 2*k(i+1)*k(i+2)/(k(i+1)+k(i+2)) else d(i) = — 2*k(i+1)*k(i+2)/(k(i+1)+k(i+2))*P_out end if end do call thomas(a,b,c,d,n) end program diff
Фортран для проектирования электростанций
! Programmer: Roberto Carlos Baldizon Diaz ! Program: gas_combustion ! Description: This program computes molar outflow rate ! of air for CH4,C2H6,C3H8,C4H10 combustion program gas_combustion implicit none ! DATA DICTIONARY: logical :: isInputValid ! legitimate: true when value entered is positive and in percentage when needed real :: a ! percentage excess air real :: rf ! signal for in flow of air theoretical real :: a1 ! moles of methane real :: a2 ! moles of ethane real :: a3 ! moles of propane real :: a4 ! moles of butane real :: nf ! molar in flow rate of air including excess (kmol/h) real :: x1 ! percentage composition of methane real :: x2 ! percentage composition of ethane real :: x3 ! percentage composition of propane real :: x4 ! percentage composition of butane real :: na ! final molar out flow of air (kmol/h) real :: o2prop ! percentage oxygen composition in air real :: ra ! signal for out flow of air theoretical ! INPUT: write(*,’(a,$)’) “Enter desired Excess Air percentage (%):” read *, a isInputValid = .TRUE. if(a < 0 .OR. a > 100) then ! Error Message write (*,*) “Desired Excess Air must be postitive and in percentage:” isInputValid = .FALSE. end if write(*,’(a,$)’) “Enter Theoretical Molar Air Flow for furnace:” read *, rf isInputValid = .TRUE. if(rf < 0) then ! Error Message write (*,*) “Theoretical Molar Air Flow for furnace must be positive:” isInputValid = .FALSE. end if write(*,’(a,$)’) “Enter desired moles of Methane for combustion:” read *, a1 isInputValid = .TRUE. if(a1 < 0) then ! Error Message write (*,*) “Composition of Methane be must positive:” isInputValid = .FALSE. end if write(*,’(a,$)’) “Enter desired moles of Ethane for combustion:” read *, a2 isInputValid = .TRUE. if(a2 < 0) then ! Error Message write (*,*) “Composition of Ethane be must positive:” isInputValid = .FALSE. end if write(*,’(a,$)’) “Enter desired moles of Propane for combustion:” read *, a3 isInputValid = .TRUE. if(a3 < 0) then ! Error Message write (*,*) “Composition of Propane be must positive:” isInputValid = .FALSE. end if write(*,’(a,$)’) “Enter desired moles of Butane for combustion:” read *, a4 isInputValid = .TRUE. if(a4 < 0) then ! Error Message write (*,*) “Composition of Butane be must positive:” isInputValid = .FALSE. end if ! PROCESS AND OUTPUT: if(isInputValid) then ! Only Compute when input was legitimate nf = (a)*(rf) end if if(isInputValid) then ! Only Compute when input was legitimate x1 = (a1)/(a1+a2+a3+a4) end if if(isInputValid) then ! Only Compute when input was legitimate x2 = (a2)/(a1+a2+a3+a4) end if if(isInputValid) then ! Only Compute when input was legitimate x3 = (a3)/(a1+a2+a3+a4) end if if(isInputValid) then ! Only Compute when input was legitimate x4 = (a4)/(a1+a2+a3+a4) end if if(isInputValid) then ! Only Compute when input was legitimate na = (nf/o2prop)*((2*x1)+ + (3.5*x2)+(0.6*x3)+(0.62x4) end if if(isInputValid) then ! Only Compute when input was legitimate nf = (inclass*.1)+(quiz*.04)+ + (progexam1*.15)+(writexam1*.13) + +(progexam2*.15)+(writexam2*.15) + +(finalproject*.08)+(finalexam*.2) end if if(isInputValid) then ! Only Compute when input was legitimate ra = (1-a)*(100) end if if(isInputValid) then ! Only Compute when input was legitimate write(*,*) “Molar flow of the fuel gas:”, nf write(*,*) “Mole fraction of Methane:”, x1 write(*,*) “Mole fraction of Ethane:”, x2 write(*,*) “Mole fraction of Propane”, x3 write(*,*) “Mole fraction of Butane:”, x4 write(*,*) “Molar flow rate of the air fed to the furnace:”, na write(*,*) “Control valve signal for air fed to furnace”, ra end if end program gas_combustion
Fortran для вычисления сдачи в монетах
! Programmer: Roberto Carlos Baldizon Diaz ! Description: This program computes change in coins. program coins implicit none ! DATA DICTIONARY integer :: cents ! Amount of change entered in cents by user integer :: quarter ! Amount of quarters (each 25 cents) user has to give back integer :: dime ! Amount of dimes (each 10 cents) user has to give back integer :: nickel ! Amount of nickels (each 5 cents) user has to give back integer :: penny ! Amount of pennies (each 1 cent) user has to give back ! INPUT CHANGE IN CENTS write(*,’(a,$)’) “Enter an amount of change in cents:” read *, cents ! OUTPUT BLANK LINE write(*,*) “” ! PROCESS quarter = cents/25 dime = (modulo(cents, 25))/10 nickel = (modulo((modulo(cents, 25)), 10))/5 penny = modulo((modulo((modulo(cents, 25)), 10)), 5) ! OUTPUT TEXT write(*,’(a,$)’) “The coins you should get back are:” ! OUTPUT BLANK LINE write(*,*) “” ! OUTPUT CHANGE write(*,*) quarter, “quarter(s)” write(*,*) dime, “dime(s)” write(*,*) nickel, “nickel(s)” write(*,*) penny, “pennies” end program coins
Fortran для сравнения веса планет с весом Земли
! Programmer: Roberto Carlos Baldizon Diaz ! Description: This lab computes weights from other planets in terms of Earth program planetweight implicit none ! DATA DICTIONARY: real :: weight ! Weight enetered by user in certain planet character :: planet ! Input planets Mercury (M), Venus (V), Mars (R) ! Jupiter (J), Saturn (S), Uranus (U), Neptune (N) ! INPUT write(*,’(a,$)’) “Enter your weight in lb:” read *, weight write*(*,’(a)’) “Select a planet where this weight was measured:”, + “(M)ercury”, + “(V)enus”, + “Ma(R)s”, + “(J)upiter”, + “(S)aturn”, + “(U)ranus”, + “(N)eptune” write(*,*) “” write(*,’(a,$)’) “Planet choice:” read *, planet write(*,*) “‘ ! PROCESS AND OUTPUT planet = achar(planet) select case(planet) case (77) weight = weight/0.37 end program planetweight
Fortran для поиска наибольшего ввода в наборе данных
! Programmer: Roberto Carlos Baldizon Diaz ! Purpose: This program determines the largest input out of a data set program largest implicit none ! DATA DICTIONARY: integer :: i ! Loop index real :: x ! Input data point real :: sum ! sum of data points real :: count ! Amount of data points collected ! INPUT/PROCESS/OUTPUT: sum = 0 ! Sum’s initial value count = 0 ! Count’s initial value do ! Process data points if(x == -1) exit write(*,’(a,$)’) “Enter another number or -1 to quit:” ! Get more data read *, x if(x /= -1) then sum = sum + x count = count + 1 end if if(x > sum .AND. x /= -1) then write(*,*) “The largest value inputed is:”, x end if end do end program largest
Fortran для нахождения площади круга
! Programmer: Roberto Carlos Baldizon Diaz ! Purpose: This program Inputs/Outputs the Area of a Circle program Circle implicit none ! Data Dictionary real, parameter :: PI = 3.1415926 ! ratio of circumference to diameter of a circle ! Data Dictionary: Variables real radius ! radius of a circle, any linear units real area ! area of same circle, square units real circum ! circumference of same circle, same linear units ! Welcome and Input write(*,’(a)’) “This program computes the area and circumference of a circle.” write(*,’(a,$)’) “What is the radius of the circle?” read *, radius ! Process area = PI*radius**2 circum = 2*PI*radius ! Output write(*,*), “” write(*,’(a, f6.3, a)’) “Area: “, area, “ sq. units” write(*,’(a, f6.3, a)’) “Circumference: “, circum, “ units” end program Circle
Fortran для сортировки наборов данных
! Programmer: Roberto Carlos Baldizon Diaz ! Description: This program will sort a list of integers in ! ascending order using a selection sort method. integer function MinIndexValue(array, start_index, end_index) ! PRE: the array(start_index) to array(end_index) is initialized ! start_index and end_index are initialized ! start_index < end_index ! POST: FCTVAL == index of the smallest element in the array ! start_index must be less than or equal to FCTVAL ! end_index must be greater than or equal to FCTVAL implicit none integer, dimension(end_index) :: array ! input array integer :: start_index ! start index value of array integer :: end_index ! logical size of array ! method variables integer :: i ! LCV integer :: min_index_value ! index value where the minimum is ! found min_index_value = start_index ! assign min as first value do i = start_index + 1, end_index, 1 ! check all values in array if(array(i) < array(min_index_value))then ! if new min is found change index ! value of min min_index_value = i end if end do MinIndexValue = min_index_value return end function MinIndexValue subroutine Swap(array, size, a, b) ! PRE: a and b both have integer values ! POST: a and b have switched values implicit none integer, dimension(size), intent(inout) :: array integer, intent(in) :: size integer, intent(in) :: a ! first value integer, intent(in) :: b ! second value ! method variables integer :: temp ! value holder for a if(a /= b) then temp = array(a) ! hold the value of a array(a) = array(b) ! give value of b array(b) = temp ! give value of original a end if end subroutine Swap subroutine SelectionSort(array, size) ! PRE: the array needs to have all integer values ! the size needs to be an integer value ! POST: the array will be sorted in ascending order implicit none integer, dimension(size), intent(inout) :: array integer, intent(in) :: size ! declare function used integer, external :: MinIndexValue ! method variables integer :: min_index_value integer :: i ! LCV do i = 1, size, 1 min_index_value = MinIndexValue(array, i, size) call Swap(array, size, i, min_index_value) end do end subroutine SelectionSort ! Test Drive program Sort_ascending implicit none ! DATA DICTIONARY integer, parameter :: MAX_SIZE = 30 ! maximum size of the list integer :: log_size ! logical size of the list integer, dimension(MAX_SIZE) :: list_original ! original list integer, dimension(MAX_SIZE) :: list_sorted ! sorted list integer :: i ! LCV ! INPUT list_original(1) = 7 list_original(2) = 8 list_original(3) = 8 list_original(4) = 0 list_original(5) = 0 list_original(6) = -1 list_original(7) = -1 list_original(8) = -50 list_original(9) = 100 log_size = 9 ! PROCESS do i = 1, log_size, 1 ! create list_sorted from list_sorted(i) = list_original(i) ! list_original end do call SelectionSort(list_sorted, log_size) ! OUTPUT write(*,*) “” ! white space write(*,’(a)’) “ Number Original Sorted” ! column headers do i = 1, log_size, 1 ! write(*,’(3i10)’) i, list_original(i), list_sorted(i) end do end program Sort_ascending
Фортран для поиска значений ASCII
! Programmer: Roberto Carlos Baldizon Diaz ! Character to ASCII Converter Program program ascii character inputChar ! input character integer asciiVal ! ASCII code for input character write(*,’(a, $)’), “Type a character: “; ! prompt for input character read *, inputChar asciiVal = iachar(inputChar) ! get its ASCII code write(*,’(a,i3)’), “ASCII code: “, asciiVal ! print out ASCII code end program ascii
Fortran для расчета стандартного отклонения набора данных
! Programmer: Roberto Carlos Baldizon Diaz ! Program: sdec ! Description: This program computes standard diviation real function mean(size,sum) ! Function to compute mean ! PRE: All vals are initializedl. size>=0 & mean>=0. ! POST: FCTVAL= Mean of the values implicit none integer, intent(in) :: size ! Size of sample real, intent(in) :: sum ! Sum of sample mean = (sum/real(size)) ! Compute mean return end function mean real function standarddev(newx,mean,size) ! Function to compute standard deviation ! PRE: All values are initialized. mean and size >=0. ! POST: FCTVAL= Standard deviation of values implicit none real, intent(in) :: newx ! Value of x(i) real, intent(in) :: mean ! Computed mean integer, intent(in) :: size ! Size of sample standarddev = sqrt(((newx-mean)**2)/(size-1.0)) ! Compute Standard Deviation return end function standarddev subroutine read(filename,size,sum,newx) ! Read file ! PRE: Filename must be inputed in main program. ! File must be correctly formatted. ! POST: Sum and size of values read sent to mainprogram implicit none character(15), intent(in) :: filename ! File to be read integer, intent(out) :: size ! Size of sample real, intent(out) :: sum ! Sum of values real, intent(out) :: newx ! Current x(i) real :: ssum ! Variable for sum real :: temp ! Temporal value integer :: count ! Count of values integer :: i ! LCV integer :: input_status ! Value of IOSTAT 0 when opened ! negative when at end of document ! positive for value not found or not read open(unit=1, file=filename, form=’formatted’, ! read file + action=’read’, status=’old’, IOSTAT=input_status) count =0 ! initiate count do ! run loop read(1,*,IOSTAT=input_status) temp ! read values if(input_status==0) then ! only do process when values are being read count = (i-count) +1 ! Keep count ssum= ssum + temp sum = ssum ! Value for sum newx = temp ! Value for x(i) end if if(input_status/=0) exit ! Exit when at end of document end do close(unit=1) ! Close unit return end subroutine read program sdec implicit none character(15), parameter :: FILENAME = ‘values.txt’ ! File to read real :: mean ! Variable for computed mean real :: standarddev ! Variable for computed standard deviation real :: sum ! Parameter Sum real :: newx ! Parameter for x(i) integer :: size ! Parameter for size call read(FILENAME,size,sum,newx) ! Subroutine write(*,*) “The mean is:”, mean ! Print mean write(*,*) “The Standard Deviation is:”, standarddev ! Print standard deviation end program sdec
Fortran для поиска максимального значения массива значений
! Programmer: Roberto Carlos Baldizon Diaz ! Section: 002 ! Description: this function finds the maximun value of an array real funtion Maximun(x, size) ! PRE: Size >0. ! POST: FCTVAL= Maximun value of Array implicit none integer intent(in) :: size ! Size of Array real, dimension(size), intent(in) :: x ! Values of Arrays integer :: i ! LCV real :: Max ! Maxiumn value of array Max = i(1) ! Initiate Max do i=2,size,1 ! Run loop if(x(i) >Max) then Max = x(i) ! Assign new Max return end if end do Maximun=Max return end function Maximun
Fortran для нахождения средневзвешенной оценки
! Programmer: Roberto Carlos Baldizon Diaz ! Program: grade ! Description: This program computes the weighted average grade that user inputs program grade implicit none ! DATA DICTIONARY: real :: inclass ! percentage grade user had in in-class assessments logical :: isGradeValid ! legitimate: true when value entered is positive and in percentage real :: quiz ! percentage grade user had in quiz real :: progexam1 ! percentage grade user had in first programming exam real :: writexam1 ! percentage grade user had in first written exam real :: progexam2 ! percentage grade user had in second programming exam real :: writexam2 ! percentage grade user had in second written exam real :: finalproject ! percentage grade user had in final project real :: finalexam ! percentage grade user had in final exam real :: classes ! amount of classes where attendance has been taken real :: attendance ! classes attended by user real :: percentattend ! percent of classes attended logical:: isAttendValid ! legitimate: true when attendaqnce is positive and in percentage real :: totalgrade ! average of user’s grades character :: lettergrade ! Variable used to represent letter grade obtained (A,B,C,D,F) ! INPUT: write(*,’(a,$)’) “Enter percentage grade of In-Class Assesments:” read *, inclass isGradeValid = .TRUE. if(inclass < 0 .OR. inclass > 100) then ! Error Message write (*,*) “Grade must be postitive and in percentage:” isGradeValid = .FALSE. end if write(*,’(a,$)’) “Enter percentage grade of Intro-Quiz:” read *, quiz isGradeValid = .TRUE. if(quiz < 0 .OR. quiz > 100) then ! Error Message write (*,*) “Grade must be postitive and in percentage:” isGradeValid = .FALSE. end if write(*,’(a,$)’) “Enter percentage grade of Programming Exam 1:” read *, progexam1 isGradeValid = .TRUE. if(progexam1 < 0 .OR. progexam1 > 100) then ! Error Message write (*,*) “Grade must be postitive and in percentage:” isGradeValid = .FALSE. end if write(*,’(a,$)’) “Enter percentage grade of Written Exam 1:” read *, writexam1 isGradeValid = .TRUE. if(writexam1 < 0 .OR. writexam1 > 100) then ! Error Message write (*,*) “Grade must be postitive and in percentage:” isGradeValid = .FALSE. end if write(*,’(a,$)’) “Enter percentage grade of Programming Exam 2:” read *, progexam2 isGradeValid = .TRUE. if(progexam2 < 0 .OR. progexam2 > 100) then ! Error Message write (*,*) “Grade must be postitive and in percentage:” isGradeValid = .FALSE. end if write(*,’(a,$)’) “Enter percentage grade of Written Exam 2:” read *, writexam2 isGradeValid = .TRUE. if(writexam2 < 0 .OR. writexam2 > 100) then ! Error Message write (*,*) “Grade must be postitive and in percentage:” isGradeValid = .FALSE. end if write(*,’(a,$)’) “Enter percentage grade of Final Project:” read *, finalproject isGradeValid = .TRUE. if(finalproject < 0 .OR. finalproject > 100) then ! Error Message write (*,*) “Grade must be postitive and in percentage:” isGradeValid = .FALSE. end if write(*,’(a,$)’) “Enter percentage grade of Final Exam:” read *, finalexam isGradeValid = .TRUE. if(finalexam < 0 .OR. finalexam > 100) then ! Error Message write (*,*) “Grade must be postitive and in percentage:” isGradeValid = .FALSE. end if write(*,’(a,$)’) “Enter amount of times attendance was taken:” read *, classes isAttendValid = .TRUE. if(classes < 0) then ! Error Message write (*,*) “Number must be positive:” isAttendValid = .FALSE. end if write(*,’(a,$)’) “Enter amount of classes attended:” read *, attendance isAttendValid = .TRUE. if(attendance < 0) then ! Error Message write (*,*) “Number must be positive:” isAttendValid = .FALSE. end if isAttendValid = .TRUE. if(attendance > classes) then ! Error Message write (*,*) “Percent attendance can not exceed 100” isAttendValid = .FALSE. end if ! PROCESS: if(isGradeValid) then ! Only Compute when grade inputed was legitimate totalgrade = (inclass*.1)+(quiz*.04)+ + (progexam1*.15)+(writexam1*.13) + +(progexam2*.15)+(writexam2*.15) + +(finalproject*.08)+(finalexam*.2) end if if(isGradeValid) then ! Only Compute when input was legitimate else if(totalgrade >= 90 .AND. percentattend >= 90) then ! Grade A lettergrade = “A” else if(totalgrade >= 80 .AND. percentattend >= 80) then ! Grade B lettergrade = “B” else if(totalgrade >= 70 .AND. percentattend >= 70) then ! Grade C lettergrade = “C” else if(totalgrade >= 60 .AND. percentattend >= 60) then ! Grade D lettergrade = “D” else ! Grade F lettergrade = “F” end if if(isAttendValid) then ! Only Compute when attendance inputed was legitimate percentattend = (attendance/classes)*100 end if if(isAttendValid) then else if(totalgrade >= 90 .AND. percentattend >= 90) then ! Grade A Attendance isAttendValid = .FALSE. else if(totalgrade >= 80 .AND. percentattend >= 80) then ! Grade B Attendance isAttendValid = .FALSE. else if(totalgrade >= 70 .AND. percentattend >= 70) then ! Grade C Attendance isAttendValid = .FALSE. else if(totalgrade >= 60 .AND. percentattend >= 60) then ! Grade D Attendance isAttendValid = .FALSE. else ! Grade F Attendance isAttendValid = .FALSE. end if ! OUTPUT: if(isAttendValid = .FALSE.) then write(*,*) “Attendance Problem” end if write(*,*) “Letter Grade”, lettergrade write(*,*) “Weighted Grade Average:”, totalgrade write(*,*) “Percent Attendance:”, percentattend end program grade
Фортран для вычислений для химических расчетов
! Programmer: Roberto Carlos Baldizon Diaz ! This program computes the rate constant of a reaction program constantrate implicit none ! DATA DICTIONARY: real, parameter :: e = 2.71828 ! exponential of natural log real, parameter :: R = 8.314 ! rate constant for Arrehmius Equation ! Data Dictionay: Variables real concentration ! concentration of the reactants in reaction real activ.energy ! energy needed to kick-start the reaction real temperature ! temperature of the reaction real rate ! rate constant of a first order Reaction ! Welcome and Input write(*,’(a)’) “This program computes the rate constant for a first order reaction.” write(*,’(a,$)’) “What is the concentration of the reaction in mol.” read *, concentration write(*,’(a,$)’) “What is the activation energy of the reaction in J.” read *, activ.energy write(*,’(a,$)’) “What is the temperature of the reaction in K.” read *, temperature ! Process rate = concentration*e**((-activ.energy)/((R/1000)*temperature)) ! Output write(*,*), “” write(*,’(a, f6.3, a)’) “Rate Constant: “, “”, rate, “1/M 1/s” end program constantrate
Fortran для чтения и вычисления данных из файлов
! Programmer: Roberto Carlos Baldizon Diaz ! Program Name: filereadcompute ! Description: This program read and computes data from a file program filereadcompute implicit none ! DATA DICTIONARY: real, parameter :: SIZE = 1000 ! Maximum amount of values in Array real, parameter :: HORIZONTAL = 4 ! Horizontal Shift for x values real, parameter :: VERTICAL = 4 ! Vertical Shift for y values real, parameter :: PI = 3.14159265 ! The ratio of any circle’s circumference ! to its Diameter integer, parameter :: OUTPUT_MODE = 1 ! Constant for the type of Output: ! 1 for Cartesian, ! 2 for polar in degrees, ! 3 for polar in radian character(15), parameter :: INPUTFILE = ‘data.txt’ ! Name of file to read character(15), parameter :: OUTPUTFILE = ‘newpoints.txt’ ! Name of file to write on integer :: i ! LCV integer :: input_status ! Status of File, 0 when open ! Negative at end of file ! and positive if not found integer :: count ! Count of points read in file real, dimension(SIZE) :: x ! Array for read x values real, dimension(SIZE) :: y ! Array for read y values real, dimension(SIZE) :: r ! Array for Magnitude of Vector ! for polar coordinates real, dimension(SIZE) :: q ! Array for computed Angles in Degrees ! for polar coordinates real, dimension(SIZE) :: qradian ! Angles converted from Degrees to radians real, dimension(SIZE) :: newx ! X values after translation real, dimension(SIZE) :: newy ! Y values after translation real :: tempx ! Temporary variable to read x values real :: tempy !INPUT: open(unit=1, file=INPUTFILE, ! Open input file + form=’formatted’, action=’read’, + status=’old’, IOSTAT=input_status) if(input_status==0) then ! Only do when ! file was opened count = 0 ! Initiate count do ! Run reading loop read(1,*, IOSTAT=input_status) tempx, tempy ! Read data ! and store in arrays if(input_status==0)then ! Only Increase Count ! when file was opened count = count + 1 ! Keep count x(count) = tempx ! Store X in Array y(count) = tempy ! Store Y in Array end if if(input_status<0)exit ! Exit at end of file end do else if(input_status>0) then ! Error Handling for ! file not found write(*,*) “File not found!” ! Error Message end if close(unit=1) ! Close input file ! PROCESS: i = 0 ! Initiate LCV if(count>0) then ! Do when input phase ! was successful do i = 1, count, 1 ! Run loop from 1 to ! count of read loop newx(i) = x(i) + HORIZONTAL ! Compute Horizontal ! Translation newy(i) = y(i) + VERTICAL ! Compute Vertical ! Translation r(i)=sqrt(newx(i)**2 + newy(i)**2) ! Compute magnitude q(i)=atan(newy(i)/newx(i)) ! Compute angles qradian(i) = q(i)*PI/180 ! Angles to radians end do end if ! OUTPUT: open(unit=2, file=OUTPUTFILE, ! Open output file + form=’formatted’, action=’write’, + status=’new’) do i = 1, count, 1 ! Run loop from 1 to ! count of read loop selectcase(OUTPUT_MODE) case(1) ! Selection of Cartesian ! Coordinates write(2,’(3a,2f7.3)’) “(“, newx(i), “,”, newy(i), “)” ! Print Cartesian ! Coordinates to File case(2) ! Selection of Polar ! Coordinates ! with angles in Degrees write(2,’(3a,2f7.3)’) “(“, r(i), “,”, q(i), “)” ! Print Polar Coordinates ! with angles in Degrees ! to File case(3) then ! Selection of Polar ! Coordinates ! with angles in radians write(2,’(3a,2f7.3)’) “(“, r(i), “,”, qradian(i), “)” ! Print Polar Coordinates ! with angles in radians ! to File end select end do write(*,*) “Translation by (“, tempx, ! Write screen message ! indicating data used + tempy, “) performed.”, “” write(*,*) “Output written to “, OUTPUTFILE ! Write screen message ! indicating new file close(unit=2) ! Close output file end program filereadcompute
Фортран для хранения дней рождения
!Programmer: Roberto Carlos Blaldizon Diaz !Purpose: Store your Birthday program birthday implicit none integer :: month ! month the user was born in # integer :: day ! day the user was born in # integer :: year ! year the user was born in # write(*,’(a)’) “Enter the month you were born (as a #):” read *, month write(*,’(a)’) “Enter the day of the month you were born:” read *, day write(*,’(a)’) “Enter the year you were born (4 digits):” read *, year write(*,’(a)’) “The birthday you entered:” write(*, *) month, “/”, day, “/”, year end program birthday
Fortran для расчета формул роста населения
! Programmer: Roberto Carlos Baldizon Diaz ! Description: Codeproduces a .csv file and computes population growth program population implicit none ! DATA DICTIONARY: real, parameter :: INITIAL = 3.9 ! Initial population in millions real, parameter :: GROWTH = 0.0298 ! Constant for population growth per year real :: population ! Computes population growth in millions real, dimension(71) :: index ! Index to hold population values integer, parameter :: STARTYR = 1790 ! Initial year evaluated in function integer, parameter :: ENDYR = 1860 ! Final year evaluated in function integer :: time ! Hold the time elapsed in array integer :: i ! LCV ! INPUT: open(unit=1, file='population4.csv', ! Create new .csv file + form='formatted', action='write', + status='new') ! PROCESS: do i = STARTYR, ENDYR, 1 ! Run Loop time = (i-STARTYR) + 1 ! Time elapsed since initial population = INITIAL*(exp(GROWTH* ! Compute Population Growth + (i-STARTYR))) time = (i-STARTYR) + 1 ! Hold time elapsed for array index(time) = population ! Store in Array end do ! End Loop ! OUTPUT: do i = STARTYR, ENDYR, 1 ! Run Loop time = (i-STARTYR) + 1 ! Time in array for population write(1,'(i4,a,4x, f9.3)') ! Write population Growth on file + i , "," , + index(time) end do close(unit=1) ! Close .csv file end program population
Как вы прочитали все представленные примеры, Fortran — отличный язык для практики и изучения кода, он также продолжает оставаться полезным инструментом для инженеров и ученых. Таким образом, используйте его, и всякий раз, когда вам нужен код для ссылки, проверьте эту статью, чтобы сохранить этот язык!
Пожалуйста, обращайтесь с любыми отзывами или сомнениями по поводу этой статьи, спасибо.
~ Роберто Балдизон