📄 unit2.pas
字号:
unit Unit2;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Grids, StdCtrls, Buttons,IdGlobal,Math;
//自己加进了delphi自带的两个库单元
type
TForm2 = class(TForm)
StringGrid1: TStringGrid;
BitBtn1: TBitBtn;
BitBtn2: TBitBtn;
BitBtn3: TBitBtn;
procedure BitBtn1Click(Sender: TObject);
procedure BitBtn3Click(Sender: TObject);
procedure BitBtn2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form2: TForm2;
implementation
{$R *.dfm}
uses unit1; //调用unit1的数据
procedure TForm2.BitBtn1Click(Sender: TObject);
var i,j,k:Integer;
bins:string;
//中间变量,存放整型转化为二进制的结果
temp:Boolean;//协助判断
hangzhi:real; //协助判断是否验证了所有的约束条件
zuiyouzhi:real;//目标函数最优值
n:Integer;//最优解的个数
begin
meijucishu:=1;
for j:=1 to VarNum do
meijucishu:=meijucishu*2;
//计算枚举次数2的n次方次,n代表变量个数
StringGrid1.ColCount:=VarNum+3;
StringGrid1.RowCount:=meijucishu+1;
//根据需要设置,文本框的行和列
for j:=1 to VarNum do
StringGrid1.Cells[j,0]:='x'+IntToStr(j);
StringGrid1.Cells[VarNum+1,0]:='函数值';
StringGrid1.Cells[VarNum+2,0]:='判断';
for i:=1 to meijucishu do
StringGrid1.Cells[0,i]:='枚举 '+IntToStr(i);
//控制结果显示界面
z:=nil;
biaoshi:=nil;
SetLength(z,meijucishu);//动态设置数组长度,存放目标函数值
SetLength(biaoshi,meijucishu);
//动态设置数组长度,表示变量组合的可行性
for k:=0 to meijucishu-1 do
begin
bins:=IntToBin(k);//将整型数转化为二进制的字符串型表示
for j:= 1 to VarNum do
begin
x[j]:=StrToInt(copy(bins,32-VarNum+j,1));
//去二进制数的最后Varnum赋给变量X
StringGrid1.Cells[j,k+1]:=IntToStr(x[j]);
//同步显示变量的取值
end;
temp:=True;
for i:=1 to ConNum do
begin
hangzhi:=0;
for j:=1 to VarNum do
hangzhi:=hangzhi+a[i,j]*x[j];
if (Sign(hangzhi-b[i])<>opt[i]) and (hangzhi<>b[i]) then
//此处巧妙的调用符号函数,并结合使用-1,0,1分别
//表示小于、等于、大于来比较变量组合是否满足第i个约束条件
begin
temp:=False;
Break;//有一个不满足,则跳出循环
end;
end;
if temp then
begin
biaoshi[k]:='+';//表示满足所有约束条件的组合
end
else biaoshi[k]:='-';//不表示满足所有约束条件的组合
for j:=1 to VarNum do
z[k]:=z[k]+x[j]*c[j]; //计算对应的目标函数值
end;
zuiyouzhi:=0;
for i:=0 to meijucishu-1 do
if leixing='Max' then//求最大化问题时,最优解的寻找
begin
if biaoshi[i]='+' then
if z[i]>zuiyouzhi then
begin
zuiyouzhi:=z[i];
end;
end
else//求最小化问题时,最优解的寻找
begin
if biaoshi[i]='+' then
if z[i]<zuiyouzhi then
begin
zuiyouzhi:=z[i];
end;
end;
//寻找最优值
n:=0;
for i:=0 to meijucishu-1 do
begin
if (abs(z[i]-zuiyouzhi)<0.000001) and (biaoshi[i]='+') then
begin //找多个最优解
biaoshi[i]:='*';
n:=n+1;
end;
StringGrid1.Cells[varNum+1,i+1]:=FloatToStr(z[i]);
StringGrid1.Cells[varNum+2,i+1]:=biaoshi[i];
end;
if n=0 then ShowMessage('该0-1规划问题无可行整数解')
else showmessage('该0-1规划问题共有'+inttostr(n)
+'个最优解'+#13+'如表中标有 * 的所示'+#13+'最优值是 '
+FormatFloat('0.#####',zuiyouzhi));
end;
{-----------程序的核心代码,计算并显示最优解和最优值------------}
procedure TForm2.BitBtn3Click(Sender: TObject);
begin
Form2.Close;
Form1.Close;//退出程序
end;
procedure TForm2.BitBtn2Click(Sender: TObject);
begin
Form1.Show; //返回到数据输入窗口
end;
end.
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -