在 Delphi 编程语言中,有多种取整函数,可以根据不同的需求选择使用。以下是一些常见的取整函数及其用法和示例:

  1. Round 函数

    • 用途:四舍五入取整。TODO 有空时 要写篇博客,研究下这个函数,这个函数不同语言的 实现方式不同,有的是标准的四舍五入,有的则是“银行家”法,为了避免各个语言出错,这个函数尽量慎用

    • 语法Round(X: Real): Int64;

    • 示例

      var
        num: Real;
        result: Integer;
      begin
        num := 3.6;
        result := Round(num); // result 为 4
        WriteLn(result);
      end;
      
  2. Trunc 函数

    • 用途:截断取整,即去掉小数部分,不进行四舍五入。
    • 语法Trunc(X: Real): Integer;
    • 示例
      var
        num: Real;
        result: Integer;
      begin
        num := 3.6;
        result := Trunc(num); // result 为 3
        WriteLn(result);
      end;
      
  3. Floor 函数

    • 用途:向下取整,返回小于或等于给定数字的最大整数。
    • 语法Floor(X: Real): Integer; (需要 Math 单元)
    • 示例
      uses
        Math;
      var
        num: Real;
        result: Integer;
      begin
        num := 3.6;
        result := Floor(num); // result 为 3
        WriteLn(result);
      
        num := -3.6;
        result := Floor(num); // result 为 -4
        WriteLn(result);
      end;
      
  4. Ceil 函数

    • 用途:向上取整,返回大于或等于给定数字的最小整数。
    • 语法Ceil(X: Real): Integer; (需要 Math 单元)
    • 示例
      uses
        Math;
      var
        num: Real;
        result: Integer;
      begin
        num := 3.2;
        result := Ceil(num); // result 为 4
        WriteLn(result);
      
        num := -3.2;
        result := Ceil(num); // result 为 -3
        WriteLn(result);
      end;
      
  5. SimpleRoundTo 函数(如果需要指定小数位数)

    • 用途:按指定的小数位数进行四舍五入。
    • 语法SimpleRoundTo(Value: Extended; Digit: Integer): Extended; (需要 SysUtils 单元)
    • 示例
      uses
        SysUtils;
      var
        num: Extended;
        result: Extended;
      begin
        num := 3.14159;
        result := SimpleRoundTo(num, 2); // result 为 3.14
        WriteLn(result:0:2); // 输出格式化为两位小数
      end;
      

这些函数在处理浮点数时非常有用,可以根据具体需求选择合适的取整方式。需要注意的是,某些函数(如 FloorCeil)需要包含 Math 单元才能使用。

posted on 2014-06-14 17:41  del88  阅读(32571)  评论(0编辑  收藏  举报