我有以下程序:
procedure GetDegree(const num : DWORD ; var degree : DWORD ; min ,sec : Extended);
begin
degree := num div (500*60*60);
min := num div (500*60) - degree *60;
sec := num/500 - min *60 - degree *60*60;
end;
分配 Degree 变量后,调试器跳到过程末尾。这是为什么?
最佳答案
这是一个优化。变量 min
和 sec
按值传递。这意味着对它们的修改不会被调用者看到,并且是该过程私有(private)的。因此,编译器可以认为给它们赋值是没有意义的。分配给变量的值永远无法读取。因此编译器选择节省时间并跳过赋值。
我希望您打算像这样声明该过程:
procedure GetDegree(const num: DWORD; var degree: DWORD; var min, sec: Extended);
正如我在上一个问题中所说,使用扩展
并没有多大意义。您最好使用标准浮点类型之一,Single
或 Double
。或者甚至使用映射到 Double
的通用 Real
。
此外,您已将 min
声明为浮点类型,但计算结果为整数。在这方面我对你之前问题的回答非常准确。
我建议您创建一条记录来保存这些值。传递三个单独的变量会使您的函数接口(interface)非常困惑并破坏封装。这三个值只有作为一个整体考虑时才有意义。
type
TGlobalCoordinate = record
Degrees: Integer;
Minutes: Integer;
Seconds: Real;
end;
function LongLatToGlobalCoordinate(const LongLat: DWORD): TGlobalCoordinate;
begin
Result.Degrees := LongLat div (500*60*60);
Result.Minutes := LongLat div (500*60) - Result.Degrees*60;
Result.Seconds := LongLat/500 - Result.Minutes*60 - Result.Degrees*60*60;
end;
function GlobalCoordinateToLongLat(const Coord: TGlobalCoordinate): DWORD;
begin
Result := Round(500*(Coord.Seconds + Coord.Minutes*60 + Coord.Degrees*60*60));
end;
关于delphi - 为什么编译器会跳过分配变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10726052/