【问题标题】:Pascal comparison error帕斯卡比较错误
【发布时间】:2014-05-15 23:14:43
【问题描述】:

我的非常简单的 Pascal 代码有问题。 (我刚开始学习 Pascal。)

所以这是一个年龄比较代码然后可以通过代码看到休息。

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.

当我输入一个低于 18 岁的值作为年龄时,我希望程序做出响应:

ACCESS DENIED
Reason:You are way to young

但我没有得到任何输出。为什么?

【问题讨论】:

  • 有什么问题?你得到了什么结果,你期望什么?
  • 是的,对不起,我忘了提。当您输入 18 岁以下的年龄时,文本不会出现,我希望它会显示该部分“writeln('ACCESS DENIED'); writeln('Reason:You are way to young');”
  • 你试过写if age&gt;18 AND age&lt;100而不是你的前2个if吗?到目前为止,您的代码似乎至少错过了一个 Begin,也许还有一个 end
  • 我试过“if age>18 AND age
  • 一些缩进,包括排列您的 if/else/end 关键字,以便您可以轻松查看程序的结构可能会有所帮助...特别是,您似乎有if age&lt;18 嵌套在 if age&gt;18 中,所以它永远不会是真的......

标签: pascal


【解决方案1】:

有时文本缩进可以帮助您发现问题。这是添加了缩进的代码:

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.

为了使实现的逻辑更明显,我现在将表示嵌套的ifs,不包含它们执行的代码:

  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
  ;

现在很容易看到标记为You are way too young 的分支永远不会到达。它应该在 age 小于 18 时执行,但是 if 语句嵌套在另一个 if 中,只有当 age 大于 18 时才会调用它。所以,age 应该首先符合条件大于 18,然后小于 18 以执行该分支 - 您现在可以看到为什么您没有得到预期的结果!

预期的逻辑可以这样实现:

  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

  ;

我相信你应该能够正确填写缺失的代码块。

最后一点:您可能希望将 age&gt;18 更改为 age&gt;=18,这样 18 岁就不会被视为“太年轻”。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-03
    相关资源
    最近更新 更多