这个delphi的while循环语句怎样写?

来源:百度知道 编辑:UC知道 时间:2024/05/26 04:12:52
从数字K到N的累加和,即若K为2,N为5,则程序代表2+3+4+5是14。要求
1.只能用while语句
2.中间应该用到IF语句以判断K和N哪个大的情况
感谢EastMagician,但回答不完整。就是当K<N时以及当K>N时两种情况,而实际只回答了前一种。我尝试加写后一种,但没有成功:
function TForm1.GetNum(iBeg,iEnd:integer):integer;
var
Num:integer;
begin
num:=0;
if iBeg<iEnd then //
while iBeg <= iEnd do
begin
Num:=Num + iBeg;
iBeg:=iBeg + 1;
Result:=Num
end
else//当开始数大于结尾数
while iEnd<=iBeg do
begin
Num:=Num + iEnd;
iEnd:=iEnd + 1;
Result:=Num;
end;
end;//结果是当开始数小于结尾数,能正确显示结果,但当结尾数小于开始数时,就出现问题。请高手指点

function GetNum(iBeg,iEnd:integer):ingteger;
var
Num:integer;
begin
if iBeg > iEnd then //iBeg iEnd互换
begin
Num:= iBeg;
iBeg:= iEnd;
iEnd:= Num;
Num:= 0;
end;
while iBeg <= iEnd do
begin
Num:=Num + iBeg;
iBeg:=iBeg + 1;
end;
Result:=Num;
end;

你要非喜欢用if就
function GetNum(iBeg,iEnd:integer):ingteger;
var
Num:integer;
begin
while 1 = 1 do //死循环
begin
Num:=Num + iBeg;
iBeg:=iBeg + 1;
if iBeg > iEnd then break; //符合条件打断
end;
Result:=Num;
end;