我一直在阅读一本教科书来学习fortran 90.目前我正在学习函数中的伪参数和局部变量。
其中一个练习是编写一个程序,询问用户的名字和姓氏,然后将名称连接在一起并打印全名。这是代码:
PROGRAM name_test
IMPLICIT NONE
! Declare variables
CHARACTER(LEN=12) :: first, last
CHARACTER(LEN=30), EXTERNAL :: full_name
! 1. Ask for first name and family name, then read them
PRINT *, "Please enter your first name"
READ *, first
PRINT *, "Please enter your family name"
READ *, last
! 2. Join names together
full_name(first, last)
! 3. Print welcome message
PRINT *, "Welcome ", full_name(first, last)
END PROGRAM name_test
CHARACTER(LEN=*) FUNCTION full_name(first_name, last_name)
IMPLICIT NONE
! Function which joins 2 names to form a full name
! Dummy argument declarations
CHARACTER(LEN=*), INTENT(IN) :: first_name, last_name
! Local variables
CHARACTER(LEN=LEN(first_name)) :: new_first_name
CHARACTER(LEN=LEN(last_name)) :: new_last_name
! Use ADJUSTL to remove redundant leading blanks
new_first_name = ADJUSTL(first_name)
new_last_name = ADJUSTL(last_name)
! Join names
full_name = TRIM(new_first_name)//" "//new_last_name
END FUNCTION full_name
当我尝试编译时,它会在第15行引用函数调用时出现错误:
full_name(first, last)
这是编译错误:
Error: Unclassifiable statement at (1)
答案 0 :(得分:1)
你在行full_name(第一个,最后一个)上有一个错误 - 虽然它给我语法错误,但可能只是编译器不同。
您正在使用的函数返回一个值,因此您可以直接在print语句中使用它。在此之前不需要使用它,即使在此之前使用它,您仍然需要将其值(它返回的值)分配给类似
的值。string = full_name(first,last)
无论如何,我把它缩短了一点,所以你走了。
program name_test
implicit none
character(len=12) :: first, last
character(len=30), external :: full_name
write(*,'("Please enter your first name : ",\)'); read(*,*)first
write(*,'("Please enter your last name : ",\)'); read(*,*)last
write(*,'("Welcome ",A)')full_name(first,last)
end program name_test
function full_name(first,last)
implicit none
character(len=*) :: first, last
character(len=30) :: full_name
full_name = trim(adjustl(first))//" "//trim(adjustl(last))
end function full_name