2014-05-15 59 views
0

我有一個非常簡單的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 

,但我沒有得到任何輸出。爲什麼?

+0

有什麼問題?你得到了什麼結果,你期望什麼? – Aserre

+0

對不起,我忘了提到這一點。 當你輸入一個18歲以下的文字不會出現 我預計它會顯示該部分「writeln('ACCESS DENIED'); writeln('原因:你是年輕的方式');」 – 21CmOfPain

+0

你有沒有試過寫'如果年齡> 18,年齡<100'而不是你的第一個2'if'?您的代碼似乎至少錯過了一個'Begin',並且可能是'end' – Aserre

回答

3

有時文本縮進可以幫助您查看問題。下面是添加了縮進代碼:

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. 

而且使實現的邏輯更加明顯,現在我將代表嵌套if•不用的代碼,他們執行:

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>18更改爲age>=18,以便18本身不符合「太年輕」的條件。

+0

非常感謝我清楚我的錯誤:D – 21CmOfPain