문제

As title says, I've just learned something called procedures in Pascal, but i bumped in one problem. So, calculator is simple and it has only 4 operations (still learning procedures). The problem is when you type in operation (+, -, * or /) it just exits the program.

Anyway, thanks in advance!

Here's the code (I wrote it in Delphi):

program Calculator;

{$APPTYPE CONSOLE}

uses
  SysUtils;

var
  n1, n2, s, m, multi, d: real;
  op: char;

procedure Sum(n1, n2: real; var s: real);
begin
  s := n1 + n2; // sum of 1st and 2nd number
end;

procedure Minus(n1, n2: real; var m: real);
begin
  m := n1 - n2 // 1st number minus 2nd number
end;

procedure Multip(n1, n2: real; var multi: real);
begin
  multi := n1 * n2; // multiplication
end;

procedure Division(n1, n2: real; var d: real);
begin
  d := n1 / n2; // division
end;

begin
  write('Insert first number: ');
  readln(n1);
  write('Insert 2nd number: ');
  read(n2);
  write('Insert operation: ');
  readln(op);
  if op = '+' then
  begin
    Sum(n1, n2, s);
    writeln('Result is: ', s);
  end
  else if op = '-' then
  begin
    Minus(n1, n2, m);
    writeln('Result is: ', m);
  end
  else if op = '*' then
  begin
    Multip(n1, n2, multi);
    writeln('Result is: ', multi);
  end
  else if op = '/' then
  begin
    Division(n1, n2, d);
    writeln('Result is: ', d);
  end;
  readln;
end.
도움이 되었습니까?

해결책

You forgot to call the ReadLn() procedure for variable n2.

By just calling Read() your program will get CR for the operator character and also the ending ReadLn() will take the last buffered CR and end the program.

When you are having trouble with your code, use the debugging possibilities to single step the program to find out what is happening.

Use Ken's advice in his comment or look into the documentation.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top