Pascal問題

2012-09-25 7:11 am
Write a program to print a set of either odd or even numbers according to the user’s will.
Example1:Enter the target: 10
Even/Odd? Even
The even numbers are 2 4 6 8 10
Example2:Enter the target: 10
Even/Odd? Odd
The odd numbers are 1 3 5 7 9
如果要咁,要點做吖???

以下係我自己做,但係錯左...:
program ex4;
var
i,num:integer;
a:string;
begin
write('Enter the target: ');
readln(num);
write('Even/Odd: ');
readln(a);
if a = 'Odd' then
write('The odd numbers are: ') ;
for i := 1 to num do
begin
write(i,' ');
i := i + 1;
end;
readln();
if a = 'Even' then
write('The even numbers are: ');
for i := i + 2 to num do
begin
write(i,' ');
i := i + 1;
end;
readln();
end.

希望有人解答到...吾該:D

回答 (1)

2012-09-25 11:07 am
✔ 最佳答案
錯誤一
for i := 1 to num do
begin
write(i,' ');
i := i + 1;
end;
作為for control用的i不宜自行在loop中加減。
錯誤二,邏輯上
if a = 'Odd' then
write('The odd numbers are: ') ;
for i := 1 to num do .....
如果要odd,if的句子可以作判斷(正確),但只限於write那一句,因為跟住的for的句子無論如何都會跑。
照你的邏輯,應該用begin end包住下面成組。
即變成
if a = 'Odd' then
begin
write('The odd numbers are: ') ;
for i := 1 to num do .....
end;
if a = 'Even' then
begin
...
end;
咁先o岩。
(三) 結構不好,如果你咁寫,會分成兩個if。入面個for又要再一次if odd(i),又或者改寫成用while或repeat until,每次加2。又或者用 i*2作even,i*2-1作為odd都得。
另一種寫法,我覺得直接及簡單一點,將個if放入for入面。即係if係決定write(i)或者唔做野。變成

for i:= 1 to num do
begin
If ((a='Odd') and (Odd(i))) or ((a='Even') and (not Odd(i))) then
write(I,' ');
end;
解:即係如果i係odd:用家又選odd,印出,或者
如果i係不是odd:用家又選Even,都印出。否則不印。


收錄日期: 2021-04-26 11:35:07
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20120924000051KK00704

檢視 Wayback Machine 備份