3. 用最优算法实现1+1/2+1/4+1/8+1/16+…..+1/n[2]的和;类别:算法类,难度:初级
我也是应届毕业生,这道题这样解可以吗?
procedure TForm1.Button1Click(Sender: TObject);
var
x,y:integer;
sum:real;
begin
sum:=0;
for x:=0 to 2do
begin
y:=up(x);
sum:=sum+1/y;
end;
label1.Caption:=floattostr(sum);
end;
function Tform1.up(n:integer):integer;
var
x,s:integer;
begin
s:=2;
if n=0 then
begin
up:=1;
end
else
begin
for x:=1 to n-1do
begin
s:=s*2
end;
up:=s;
end;
end;