我在写很长的数字节律。这是一个用于向长度较长的二进制数字添加的函数。我需要在函数内部输出sum,以便对其进行调试。我怎么才能做到这一点,而不创建新的变量呢?
function add(var s1,s2:bindata;shift:longint):bindata;
var l,i:longint;
o:boolean;
begin
writeln(s1.len,' - ',s2.len);
o:=false;
l:=max(s1.len,s2.len);
add.len:=0;
for i:=1 to l do begin
if o then Begin
if s1.data[i+shift] then Begin
if (s2.data[i]) then add.data[i+shift]:=true
Else add.data[i+shift]:=false;
End
else if s2.data[i] then add.data[i+shift]:=false
else Begin
add.data[i+shift]:=true;
o:=false;
End;
End
Else Begin
if s1.data[i+shift] then Begin
if s2.data[i] then
Begin
add.data[i+shift]:=false;
o:=true;
End
Else add.data[i+shift]:=true;
End
else if s2.data[i] then add.data[i+shift]:=true
else add.data[i+shift]:=false;
End;
output(add); //Can I output a variable?
end;
add.len:=l;
if o then Begin
inc(add.len);
add.data[add.len]:=true;
End;
end;发布于 2013-12-18 01:39:04
您在函数结果变量中累积了函数的结果,这通常很好,但使用了过时的样式,并导致了您在这里所面临的问题。您正在尝试报告函数结果的中间值,为此,您正在尝试引用函数的名称add。但是,当您这样做时,编译器会将其解释为尝试报告函数本身,而不是该函数的此特定调用的预期返回值。如果将output定义为接受函数地址,您将获得函数的地址;否则,您将获得编译器错误。
如果您的编译器提供了某个公共语言扩展,那么您应该使用隐式的Result 变量来引用中间返回值,而不是继续通过函数名来引用它。因为Result是隐式声明的,所以您不必创建任何其他变量。编译器自动识别Result并将其用作函数返回值的别名。只需在函数中找到您编写add的每个位置,并将其替换为Result。例如:
if o then begin
Inc(Result.len);
Result.data[Result.len] := True;
end;Turbo Pascal、Free Pascal、GNU Pascal和Delphi都支持隐式Result变量,但是如果您设法使用不提供该扩展的编译器,那么您别无选择,只能声明另一个变量。您可以将其命名为Result,然后在末尾添加一行来实现您的函数,如下所示:
function add(var s1, s2: bindata; shift: longint): bindata;
var
l, i: longint;
o: boolean;
Result: bindata;
begin
{
Previous function body goes here, but with
`add` replaced by `Result`
}
{ Finally, append this line to copy Result into the
function's return value immediately before returning. }
add := Result;
end;https://stackoverflow.com/questions/16505874
复制相似问题