Pascal comparison error

前提是你 提交于 2019-12-25 12:47:11

问题


I have a problem with my very simple Pascal code. (I just started to learn Pascal.)

So it's about an age comparison code then rest can be seen through the code.

program Test;
uses crt;
var
  age : real;
Begin

writeln('Enter your age: ');
readln(age);
if age>18 then
if age<100 then
Begin
clrscr;
textcolor(lightgreen);
writeln('Access Granted');
end
else
if age<18 then
Begin
clrscr;
textcolor(lightred);
writeln('ACCESS DENIED');
writeln('Reason:You are way to young');
end
else
Begin
clrscr;
textcolor(lightred);
writeln('ACCESS DENIED');
writeln('Reason:You are way to old');
end;
readln;
end.

When I enter a value below 18 as the age, I expect the program to respond:

ACCESS DENIED
Reason:You are way to young

but I don't get any output. Why?


回答1:


Sometimes text indentation helps you to see the issue. Here's your code with indentation added:

program Test;
uses crt;
var
  age : real;
Begin
  writeln('Enter your age: ');
  readln(age);
  if age>18 then
    if age<100 then
    Begin
      clrscr;
      textcolor(lightgreen);
      writeln('Access Granted');
    end
    else
      if age<18 then
      Begin
        clrscr;
        textcolor(lightred);
        writeln('ACCESS DENIED');
        writeln('Reason:You are way to young');
      end
      else
      Begin
        clrscr;
        textcolor(lightred);
        writeln('ACCESS DENIED');
        writeln('Reason:You are way to old');
      end;
  readln;
end.

And to make the implemented logic more obvious, I will now represent the nested ifs without the code that they execute:

  if age>18 then
    if age<100 then
      ...  // Access Granted
    else
      if age<18 then
        ...  // You are way too young
      else
        ...  // You are way too old
  ;

It is easy to see now that the branch marked as You are way too young is never reached. It is supposed to be executed when age is less than 18, but that if statement is nested into another if which will call it only when age is greater than 18. So, age should first qualify as greater than 18, then less than 18 in order for that branch to execute – you can see now why you do not get the expected result!

The intended logic could possibly be implemented this way:

  if age>18 then

    if age<100 then
      ...  // Access Granted
    else  // i.e. "if age >= 100"
      ...  // You are way too old

  else  // now this "else" belongs to the first "if"

    ...  // You are way too young

  ;

I believe you should be able to fill in the missing code blocks correctly.

Just one last note: you might want to change age>18 to age>=18, so that 18 proper does not qualify as "too young".



来源:https://stackoverflow.com/questions/23680039/pascal-comparison-error

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!