欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Pascal基本用法

程序员文章站 2022-04-05 12:36:42
...
 
var  
    x, y, max, num : integer;
    name : string;        {define a variable}
    const PI = 3.1415926; {define a constant}
begin
    assign(output, 'bbb.out'); {write output to file}
    reset(input);
    rewrite(output);

    {1. arithmetic operation}
    x := 10;
    y := 20;
    writeln('x + y = ', x + y); {free pascal not support IntToStr, but remeber to use in Delphi}
    writeln('x - y = ', x - y);
    writeln('x * y = ', x * y);
    writeln('x / y =1 ', x div y);

    writeln('x % y = ', x mod y);

    {2. relational operator and conditional operation}
    if x > y then
    begin
        max := x;
        writeln('x is large than y');
    end
    else if x = y then
    begin
        max := x;
        writeln('x is equals to y');
    end
    else begin
        max := y;
        writeln('x is less than y');
    end;

    writeln('max of x and y is : ', max);

    {3. boolean operator. If has more than one boolean operation in if, use () to surround each boolean operation.Otherwise, error will occur.}
    if (x=y) or (x<y) then
        writeln('x is less or equals y');

    {4. loop }
    num := 10; {attention: operation of assigning value shoud be put in begin statement other than var statement}
    writeln('======== while loop start =======');
    while num>0 do
    begin
        writeln('loop, num= ', num);
        num := num - 2;
    end; {attention: don't forget ';' after end}
    writeln('===== while loop end =====');

    writeln('======= for loop start ======');
    for num := 0 to 5 do
    begin
        writeln('loop, num= ', num);
    end;

    close(input);
    close(output);
end.
注意事项:

1) 变量及常量的定义需要放在var声明中,而变量的赋值操作必须放在begin下面

2) 程序中通过write、writeln输出内容,两种的区别是writeln输出内容后会回车换行

3) 如果使用Free Pascal IDE运行程序,运行之后界面一闪而过,这是因为程序运行较快,运行完成后又回到了

IDE界面。如果希望看到运行结果,可以在程序结束 添加 readln; 这样的话,程序运行之后会等待输入任意键,

输入完成后,才会回到IDE界面。也可以使用 Alt + F5 快捷键回到运行结果界面。另外,也可以使用输入输出流

将结果写入文件中,如下:

{begin下}
assign(input,'*.in');     {第二个参数为输入文件名,下行为输出文件名,因题而变}
assign(output,'*.out');
reset(input);
rewrite(output);

{业务代码}

close(input);
close(output);

4) if语句中如果有多个条件,则每个条件都要用括号括起来,不然会报错(应该是运算符优先级导致的,还没研究)

5) 开头的begin 需要 end. 与之对应,否则会报错: Syntax error, '.' expected but "end of file" found (Free Pascal中)

相关标签: pascal