簡單的 IO

作為寫入輸入和輸出的示例,我們將獲取實數值並返回值及其平方,直到使用者輸入負數。

如下所述,read 命令有兩個引數:單元號和格式說明符。在下面的示例中,我們使用*作為單元號(表示 stdin)和*作為格式(在這種情況下表示 reals 的預設值)。我們還指定了 print 語句的格式。也可以使用 write(*,"The value....") 或者簡單地忽略格式化並將其作為

print *,"The entered value was ", x," and its square is ",x*x

這可能會導致一些奇怪的間隔字串和值。

program SimpleIO
   implicit none
   integer, parameter::wp = selected_real_kind(15,307)
   real(kind=wp) :: x
   
   ! we'll loop over until user enters a negative number
   print '("Enter a number >= 0 to see its square. Enter a number < 0 to exit.")'
   do
      ! this reads the input as a double-pricision value
      read(*,*) x
      if (x < 0d0) exit
      ! print the entered value and it's square
      print '("The entered value was ",f12.6,", its square is ",f12.6,".")',x,x*x
   end do
   print '("Thank you!")'
   
end program SimpleIO