Nhập vào giá trị n (n>2) . Tính tổng các giá trị chẵn trong phạm vi từ 2 đến n Sử dụng câu lệnh while-do

2 câu trả lời

uses crt;
var n, i, s : integer;
begin
clrscr;
write(' nhap so n :'); readln(n );
i := 2;
s := 0;
while (i <= n) do
begin
if i mod 2 =  0 then s := s + i;
i := i + 1;
end;
writeln(' tong so chan tu 2 den ', n ,' la :', s );
readln
end.

$#QLinkVN$

Cấu trúc chương trình cụ thể như sau:

program chan_le;
uses crt;
var i,n,tong: integer;
begin
clrscr;
writeln('Nhap gia tri cuoi n: '); readln(n);
i:=2; tong:=0;
while i<=n do
begin
if (i mod 2=0) then tong:=tong+i;
i:=i+1;
end;
writeln('Tong cua day so chan tren la: ',tong);
readln;
end.

Giả sử khi nhập giá trị "n" là 10 thì theo cách tính bình thường thì ta có: "2+4+6+8+10=30"

Khi nhập vào giá trị "n" là 10 thì kết quả của chương trình cũng cho ra đáp án tương tự. (xem hình)

Câu hỏi trong lớp Xem thêm
5 lượt xem
2 đáp án
19 giờ trước

giup e voi I/ Supply the correct form of the verbs in brackets 1. You (think) ……………………… collecting stamps costs much money? 2. Every year, my mother (give) ……………………… me a nice doll on my birthday. 3. Jenny says she loves collecting pens but she (not/continue) ……………………… this hobby from next year. 4. If you wash your hands more, you (have)……………………. less chance of catching flu. 5. Getting plenty of rest is very good. It (help)…………………. you to avoid depression. 6. Mr. John (be) ……………………… principal of our school since last year. 7. I (see) ……………………… a car accident on this corner yesterday. 8. We like (come)……………………to school by bus, but we hate (stand)………………………. and (wait) …………………… in the rain. 9. ……………………… (you/ ever/ meet) anyone famous? 10. My mother (come) ……………………… to stay with us next weekend. 11. When he lived in Manchester, he (work) ……………………… in a bank. 12. We (be) ……………………… students for four years. 13. We are planting trees around our school now. Our school (be) ……………………… surrounded by a lot of green trees. 14. What ……………………… your father usually ……………………… (do) in the evenings? 15. My sister likes (cook) ……………………… very much. She can cook many good foods. 16. My father says when he's retired, he (go) …………………… back to his village to do the gardening. 17. They want (buy) ……………………… some meat for dinner. 18. Linh is my best friend. We (know) ……………………… each other for 5 years. 19. I enjoy (fish) ……………………… because it is relaxing. 20. How about (go) ……………………… to the movie theatre?

3 lượt xem
1 đáp án
1 ngày trước