将数据保存在另一个外部文件名output.txt中?

时间:2014-04-12 09:51:41

标签: fortran

程序可以运行,我不知道如何使用open()并将数据保存在另一个外部文件名output.txt中。我的问题如下所示 - 请看看并帮助。

program start
implicit none
integer ::n

real(kind=8)::x,h,k
real(kind=8),external:: taylorq
x=1.0
n=20
h=exp(x)
k=taylorq(x,n)

open(10,'output.txt') ----------- *question1:(when should i put       this open file?)*
write(*,*)"The exact value=",h
write(*,*)"The approximate value=",k
write(*,*)"The error=",h-k
end program start

function taylorq(x,n)
implicit none
integer::n,i
real(kind=8):: x,taylor,taylor2,taylorq,h
h=exp(x)
taylor=1.
taylor2=taylor
write(*,*)"i    exact   appro   error"-----------question2:(actually I want to draw a table with subtitle i, exact, appro, error in each column, is there a nice way to arrange them like eg.we can use %5s)

do i=1,n
taylor=taylor*x/i
taylor2=taylor2+taylor
write(10,*)i,h,taylor2,taylor2-h --------question3:*(I want to save the data written here into file output.txt)*
end do
close(10)
taylorq=taylor2

 end function taylorq

1 个答案:

答案 0 :(得分:2)

1。在哪里打开

你应该打开(10,...),以便在任何写入(10,...)之前执行 - 或者如果输入则读取(10,...)。 由于您的写入发生在函数taylorq中,因此您应该在调用taylorq的语句之前打开()。

对于进行大型计算的程序,Fortran适合/着名的程序,通常最好这样做 所有文件都在程序开头附近打开,因此如果打开任何文件时出现问题, 它被抓住并修复而不浪费时间或工作日。但是你的程序要简单得多。

2。格式化

是的,Fortran可以进行格式化输出 - 也可以格式化输入。而不是文本字符串 插值说明符(如C和C部分的C ++,Java,以及awk和perl和shell)它使用说明符 使用可选的插值文本值,并使用格式字母写入说明符 左边的跟随宽度(几乎总是)和其他参数(有时)。

您可以将格式直接放在WRITE(或READ)语句中,也可以放在单独的FORMAT中 其标签在I / O声明中引用的声明。

write (10, '(I4,F10.2,F10.2,F10.2)' ) i,h,taylor2,taylor2-h

write (10, 900) i,h,taylor2,taylor2-h
! this next line can be anywhere in the same program-unit 
900 format (I4,F10.2,F10.2,F10.2)

与C系列语言不同,Fortran将始终输出指定的宽度;如果价值不合适, 它会打印星号*****,而不是强制字段更宽(因此未对齐)(或截断为 COBOL做!)。你的系列增长得足够快,你可能想要使用像E10.3这样的科学记数法。 (格式字母可以是任何一种情况,但我发现它们更容易在上面阅读.YMMV。)

有很多很多选择。任何教科书或编译器手册都应该涵盖这一点。