Illegal Expression on Pascal

177 views Asked by At
program latihan;
uses crt;

var
    a, b, c : integer;
    d : real;

begin
    write('a: ');
    readln(a);
    write('b: ');
    readln(b);
    c := a + b;
    d := a + b;
    sqr(c);
    writeln(c);
    sqrt(d);
    writeln(d:0:0);
end.

why there's an illegal expression at code sqrt(d) ??

what is the explanation why there can be an illegal expression at the sqrt(d) code and how to fix it?

3

There are 3 answers

4
Hoàng Hải Lý On

The sqrt() function in Pascal only works on integer types, while d is a real type. So trying to pass a real value to sqrt() results in an illegal expression error.

To fix this, you need to use a different square root function that supports real numbers, such as:

uses Math;

//...

sqrt(d);

Alternatively, you can convert d to an integer first before using sqrt():

c := trunc(d);
sqrt(c);
0
Trome On

sqrt() returns an Extended value, to receive the result you need to assign it to a variable, the same for sqr():

c := sqr(c);
writeln(c);
d := sqrt(d);
writeln(d);
0
tofro On

sqrt() is a function returning a value and needs to be used as that. You used it like a procedure.

Functions need their return value assigned to variables, like in

    c := sqrt (c);

The variable you assign the return value of sqrt() to needs to be a REAL type.