PDA

View Full Version : Giúp em về câu lệnh case of trong pascal với mấy pác !?



nguabay91
20-05-2011, 07:35
các pác ơi tình hình là như thế này
em có chương trình viết bằng pascal như thế này:

program Tinh_lua_tuoi;
uses crt;
var
ho_ten: string[20];
namsinh, namnay, tuoi: integer;
phanloai: string[14];
begin
clrscr;
write('Nhap ho va ten: ');
readln(ho_ten);
write('Nhap nam sinh: ');
readln(namsinh);
write('Nhap nam nay: ');
readln(namnay);
tuoi:= namnay - namsinh;
if tuoi < 0 then writeln('Nhap sai')
else
begin
case tuoi of
0, 1: phanloai:= 'So sinh';
2..9: phanloai:= 'Nhi Dong';
10..15: phanloai:= 'Thieu nien';
16..32: phanloai:= 'Thanh nien';
33..50: phanloai:= 'Trung nien';
else
phanloai:= 'Nguoi lon tuoi';
end;
writeln(ho_ten, #32, tuoi, #32, phanloai);
end;
readln;

end.

vậy pác nào là pro về programing cho em hỏi làm sao để thay câu lệnh case of trên bằng các câu lệnh if then trong pascal ?
mọi người nhớ dúp em với nha em đang cần gấp
mọi người cho em thank ! trước nà :D
em xin cảm ơn và hậu tạ !

1hakunamatata
23-05-2011, 20:58
case tuoi of
0..1: phanloai:= 'So sinh';
2..9: phanloai:= 'Nhi Dong';
10..15: phanloai:= 'Thieu nien';
16..32: phanloai:= 'Thanh nien';
33..50: phanloai:= 'Trung nien';
else
phanloai:= 'Nguoi lon tuoi';
end;



if (0<=tuoi) and (tuoi<=1) then phanloai:='sosinh';
if (2<=tuoi) and (tuoi<=9) then phanloai:='nhidong';
if (10<=tuoi) and (tuoi<=15) then phan loai:='thieu nien';
if (16<=tuoi) and (tuoi<=32) then phan loai:='thanh nien';
if (33<=tuoi) and (tuoi<=50) then phan loai:='trung nien' else phanloai:='nguoi lon tuoi';

nguabay91
24-05-2011, 09:27
anh gì ơi không được mô em thử rùi
nhưng em nghĩ có lẽ phải thêm else vao nữa
nhưng dù sao cũng cảm ơn vì đã dúp dỡ :D

truong92cdv
29-05-2011, 13:30
if (0<=tuoi) and (tuoi<=1) then phanloai:='sosinh';
if (2<=tuoi) and (tuoi<=9) then phanloai:='nhidong';
if (10<=tuoi) and (tuoi<=15) then phan loai:='thieu nien';
if (16<=tuoi) and (tuoi<=32) then phan loai:='thanh nien';
if (33<=tuoi) and (tuoi<=50) then phan loai:='trung nien' else phanloai:='nguoi lon tuoi';

Chào bạn, đoạn lệnh của bạn không đúng là vì nếu viết như vậy thì 4 câu lệnh
if (0<=tuoi) and (tuoi<=1) then phanloai:='sosinh';
if (2<=tuoi) and (tuoi<=9) then phanloai:='nhidong';
if (10<=tuoi) and (tuoi<=15) then phan loai:='thieu nien';
if (16<=tuoi) and (tuoi<=32) then phan loai:='thanh nien';
xem như ko tồn tại, bởi vì đặc điểm của câu lệnh if else cuối cùng đã ảnh hưởng đến KQ. Bạn có thể cho tuoi = 15 rồi thử chạy từng đoạn lệnh sẽ hiểu.
Muốn làm theo kiểu này thì bạn hãy thay câu lệnh cuối cùng bằng 2 câu lệnh sau:
if (33<=tuoi) and (tuoi<=50) then phan loai:='trung nien';
if tuoi>50 then phan loai:='nguoi lon tuoi';