gpt4 book ai didi

c# - 在 C# 中实现此 Fortran 片段的最佳方法是什么

转载 作者:太空宇宙 更新时间:2023-11-03 14:09:09 25 4
gpt4 key购买 nike

我有一个 Fortran 例程,它从这样的文件中读取数据:

10   READ(X,*,ERR=8000,END=9000) ... Read header line of data sequence
C Some processing of header line data...
READ(X,*,ERR=8000) ... Read secondary line of data sequence
C Some processing of secondary line data...
20 READ(X,*,ERR=8000) ... Read data line
IF data contains 'X' GOTO 10
C Do some calculations with the data ...
IF (X.LT.Y)
GOTO 10
C Do some more calculations ...
100 CONTINUE
8000 'Output some error to the log'
9000 'Some final stuff'
RETURN

原始代码比这长很多,但这是要点。我认为像下面这样的 C# 代码应该做同样的事情(从内存编码,所以可能会出现一些错误......),但出于某种原因,这似乎非常复杂以达到相同的结果。是否有一种简单的方法来复制 Fortran 例程的流程?这只是使用 gotos 提供比使用代码块更短的代码的情况吗?

private void MyFunction(Stream MyData)
{
string s = string.Empty;
bool flag;
StreamReader sr = new StreamReader(MyData);
try
{
while (!sr.EndOFStream)
{
s = sr.ReadLine(); ... Read header line of data sequence
//Some processing of header line data ...
s = sr.Readline(); ... Read secondary line of data sequence
//Some processing of secondary line data ...
flag = false;
while (!(s = sr.ReadLine()).Contains("X"))
{
//Do some calculations with the data ...
if (X < Y)
{
flag = true;
break;
}
//Do some more calculations ...
}
if (flag) continue;
}
//Some final stuff ...
return;
}
catch
{
//Output error to log...
}
}

最佳答案

当然可以避免 goto 语句。

但在我看来,您的 C# 示例与 Fortran 代码片段的功能不同(至少我是这么认为的)。我不懂 C#,但这是没有 goto 的 Fortran 版本。它应该等同于另一个版本,但有一个异常(exception):我没有包括 I/O 错误检查。

 readloop : do while(.true.)
read(X,*,iostat=stat) ! ... Read header line of data sequence
if (stat /= 0) exit
! Some processing of header line data...
read(X,*) ! ... Read secondary line of data sequence
! Some processing of secondary line data...
read(X,*) ! ... Read data line
if (data contains 'X') cycle readloop
! Do some calculations with the data ...
if (X >= Y) exit readloop
end do
! Some final stuff

这应该转换为 C#-ish 代码(我从您的代码示例中推断出语法):

 while (!sr.EndOfStream) {
s = sr.ReadLine();
// process
s = sr.ReadLine();
// process
s = sr.ReadLine();
if (s.Contains("X")) continue;
// calculations
if (X >= Y) break;
}
// final processing

在这里使用 try...catch 结构进行错误检查应该很简单。

关于c# - 在 C# 中实现此 Fortran 片段的最佳方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8410686/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com