中山大学面向对象Delphi期中
作业答案
(提交Delphi
源代码和exe文件)
一、编写相应的
Delphi程序,分别实现以下科学计算功能:
1. 利用公式
e?
1?
1 1!
?
1 2!
?
1 3!
????
1 n!
编出程序计算自然对数底e,精确到10-6
。 [解答]
unit NaturalLog; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls,math; type
TForm1 = class(TForm)
Label1: TLabel;
Edit1: TEdit;
Button1: TButton;
Button2: TButton;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Edit2: TEdit;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
function factorial(n:integer):double;
var i:integer;
prod:double;
begin
prod:=1;
if n>0 then
begin
for i:=2 to n do
prod:=prod*i;
factorial:=prod;
end
else
if n=0 then factorial:=1
else showmessage('阶乘参数不能为负数!')
end;
var
eps,addor,s:double;
i,max_i:integer;
begin
eps:=strtofloat(edit1.Text);
max_i:=strtoint(edit2.Text);
i:=1;
s:=1;
repeat
addor:=1/factorial(i);
s:=s+addor;
i:=i+1;
until ((i>max_i) or (addor
if i>max_i then
label2.Caption:='不收敛,迭代次数超过:'+edit2.text
else
label2.Caption:='级数收敛于:'+floattostr(s)+' '+chr(13)+'迭代次数:'+floattostr(i);
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
close;
end;
end.
1231234 ?1??? ? 2. 利用公式 2 3353573579 编出程序计算 ?。
unit uround; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls,math; type TForm1 = class(TForm) Label1: TLabel; Edit1: TEdit; Button1: TButton; Button2: TButton; Label2: TLabel; Label3: TLabel; Label4: TLabel; Edit2: TEdit; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.Button1Click(Sender: TObject); var eps,addor,s:double; i,max_i:integer; begin
eps:=strtofloat(edit1.Text);
max_i:=strtoint(edit2.Text);
i:=1;
s:=1;
addor:=1;
repeat
addor:=addor*i/(2*i+1);
s:=s+addor;
i:=i+1;
until ((i>max_i) or (addor if i>max_i then
label2.Caption:='计算不收敛,迭代次数超过:'+edit2.text
else
label2.Caption:='Pi的近似值为:'+floattostr(2*s)+' '+chr(13)+'迭代次 数:'+floattostr(i);
end;
?
112
3. 计算级数
?
?
3
n
n?1
n!
,精确到10-6
.
?
要点:取不断增大的n值,计算?
3
n
的值,比较值的变化。
n?1
n!
procedure TForm1.Button1Click(Sender: TObject); function factorial(n:integer):double; var i:integer; prod:double; begin prod:=1; if n>0 then begin for i:=2 to n do prod:=prod*i; factorial:=prod; end else if n=0 then factorial:=1 else showmessage('阶乘参数不能为负数!') end; var eps,addor,s:double; i,max_i:integer; begin
eps:=strtofloat(edit1.Text);
max_i:=strtoint(edit2.Text);
i:=1;
s:=0;
repeat
addor:=power(3,i)/factorial(i);
s:=s+addor;
i:=i+1;
until ((i>max_i) or (addor if i>max_i then
label2.Caption:='不收敛,迭代次数超过:'+edit2.text
else
label2.Caption:='级数收敛于:'+floattostr(s)+' '+chr(13)+'迭代次 数:'+floattostr(i);
end;
4. 编写一个判断某数是否为素数的应用程序,程序的设计界面如图所示。 程序运行时,在编辑框中输入任意一个正整数,单击【判断】按钮,在另一个编 辑框显示该数是否为