實現(xiàn)上述功能的VB程序如下,但加框處代碼有錯,請改正。 Private Sub Command1_Click ( ) Dim x As Integer,y As Integer,i As Integer,j As Integer,b As Integer,ans As Integer ans=0 For x=100To 5000 y=0 b=0 For i=1To x\2 If x Mod i=0Then y=y+i Next i For j=1Toy\2 If y Mod j=0Then b=b+j Next j If Then'① List1.AddItem Str(x)+Str(y) ans=ans+1 End If Next x '② End Sub
算法思想: (1)首先計算出n件物品的單位價值(單位價值=價值/體積); (2)將物品按單位價值降序排序; (3)然后依次從單位價值最大的物品開始裝入背包,直到裝滿整個背包為止。 (4)輸出裝入背包的物品的相關(guān)信息。 實現(xiàn)上述功能的程序如下,請在程序橫線處填入合適的語句或代碼。 Dim conn As New ADODB.Connection Dim rs As New ADODB.Recordset Dim id(1To 20)As String'存儲物品的id號 Dim jz(1To 20)As Long,tj(1To 20)As Long'數(shù)組jz、tj分別存儲物品的價值和體積 Dim dwjz(1To 20)As Single'存儲物品的單位價值 Dim n As Integer'表示物品數(shù) Private Sub Command1_Click ( ?。?br />'讀取數(shù)據(jù)庫表中前n條記錄的信息 End Sub Private Sub Command2_Click ( ) Dim m As Integer,i As Integer,j As Integer,p As Integer,tp1As String,tp2As Integer Dim tp3As Single m=Val(Text2.Text) For i=1To n dwjz(i)=jz(i)/tj(i) Next i For i=1To n-1 For j=n To i+1Step-1 If ①Then tp1=id(j):id(j)=id(j-1):id(j-1)=tp1 tp2=jz(j):jz(j)=jz(j-1):jz(j-1)=tp2 tp2=tj(j):tj(j)=tj(j-1):tj(j-1)=tp2 tp3=dwjz(j):dwjz(j)=dwjz(j-1):dwjz(j-1)=tp3 End If Next j Next i i=1 p=n ans=0 List2.AddItem“編號“+“價值“+“體積“+“裝入背包的體積“ Do While m>0Andp>=1 If m-tj(i)>=0Then ans=ans+jz(i) List2.AddItem id(i)+““+Str(jz(i))+““+Str(tj(i))+““+Str(tj(i)) Else ② List2.AddItem id(i)+““+Str(jz(i))+““+Str(tj(i))+““+Str(m) End If m=m-tj(i) i=i+1 ③ Loop List2.AddItem“背包總價值為:“+Str(ans) End Sub