delphi 检查一个数字是否在free pascal的范围内

ql3eal8s  于 12个月前  发布在  其他
关注(0)|答案(4)|浏览(116)

我试图找出正确的方法来传递一个使用Free Pascal case语句的例子到一个简单的if语句。
用例将是

begin usingCaseStatements;

var
  user_age : Integer;

begin

  Writeln('Please enter your age');
  Readln(user_age);

  case user_age of
  1..12 : Writeln('You are too young');
  else
    Writeln('Invalid input');
  end;

  Writeln('Please any key to terminate the program');
  Readln();
end.
  • 使用if语句-
begin usingCaseStatements;

var
  user_age : Integer;

begin

  Writeln('Please enter your age');
  Readln(user_age);

  if user_age in 1..12 then
    Writeln('You are too young')
  else
    Writeln('Invalid input');
  Writeln('Please any key to continue');
  Readln();
end.

我试过替换if语句片段中的“in”,但没有任何运气,我试过做if (user_age = 1..12) then,它只给了我一个错误,编译器说语句正在等待“)”,但它发现..相反。我是非常新的FPC,所以帮助和提示将不胜感激。

whlutmcx

whlutmcx1#

  • IN* 测试用于集合,而不是范围。正如TLama已经评论过的,你可以使用[1..12]定义一个包含范围的集合。

大多数PC Pascals只支持最多256个元素的设置大小,所以从长远来看,josifoski推荐的解决方案更实用。

f2uvfpb9

f2uvfpb92#

如果(user_age >=1)和(user_age <=12),则

anhgbhbe

anhgbhbe3#

语句if user_age in 1..12 then非常像Ada语法。Free Pascal是比较接近的:if user_age in [1..12] then
下面是一个简单的可编译示例:

Program inRange;

var
  int1 : integer = 45;

begin
  if int1 in [4..200] then
    writeln('int1 is between 4 and 200')
  else
    writeln('int1 is not between 4 and 200')
end.

输出量:

Free Pascal Compiler version 3.2.2 [2021/05/15] for i386
Copyright (c) 1993-2021 by Florian Klaempfl and others
Target OS: Win32 for i386
Compiling scratch6.pas
Linking scratch6.exe
12 lines compiled, 0.1 sec, 28288 bytes code, 1332 bytes data

int1 is between 4 and 200
iqjalb3h

iqjalb3h4#

只是为了好玩。它在FPC 2.7.1上工作,但我不知道它是否会在稳定的2.6.4上工作

program project1;

{$modeswitch typehelpers}

type
    TIntegerHelper = type helper for Integer
        function IsInRange(const ALow, AHigh: Integer): Boolean; inline;
    end;

    function TIntegerHelper.IsInRange(const ALow, AHigh: Integer): Boolean; inline;
    begin
        Result := (Self >= ALow) and (Self <= AHigh);
    end;
var
    i: Integer;

begin
    i := 8;
    Writeln(i.IsInRange(7, 9));
    Writeln(i.IsInRange(8, 8));
    Writeln(i.IsInRange(2, 3));
    Readln;
end.

输出量:

TRUE
TRUE
FALSE

相关问题