按上述要求,编写VB程序,功能如下:在文本框Text1中输入预计礼物数,在文本框 Text2中输入总金额,单击“计算”按钮Command1,在列表框List1中显示各类商品的编号、单价、数量、喜爱度,以及最佳购买方案、剩余金额和总喜爱度,若有多种最佳方案,则输出第一个找到的方案信息,如图a所示。
图a |
Const m = 4 '有 m 种商品
Dim sph(1 To m) As String '商品号
Dim dj(1 To m) As Single '单价
Dim sl(1 To m) As Integer '数量
Dim xa(1 To m) As Integer '喜爱度
Dim hh(1 To m * 10) As Integer '每件商品对应的货号
Dim p As Integer,n As Integer,nc As Integer 'p个朋友,n元钱,共nc件商品
Dim zxa As Integer '总喜爱度为每件购买商品的喜爱度*购买数量的总和
Private Sub Form_Load()
'各商品的商品号、单价、数量、喜爱度分别存入数组 sph、dj、sl 和 xa 并输出,代码略
End Sub
Private Sub Command1_Click()
Dim goumai(1 To m * 10) As Integer
Dim i As Double,j As Integer,k As Integer,t As Integer
Dim fs As Integer,je As Integer,maxi as Integer,maxje As Integer,maxzxa As Integer
p = Val(Text1.Text): n = Val(Text2.Text)
nc = 0
For i =1 To m
For j =1 To sl(i)
nc = nc + 1: ①
Next j
Next i
For i =0 To 2^ nc - 1
t = i
For j =1 To nc
goumai(j) =②
t = t \ 2
Next j
fs = 0: je = 0: zxa =0 '初始化份数,金额,总喜爱度
For j =1To nc
fs = fs + goumai(j): je = je + dj(hh(j)) * goumai(j): zxa = zxa + xa(hh(j)) * goumai(j)
Next j
If fs = p And ③ Then maxi = i: maxje = je: maxzxa = zxa
Next i
'输出maxi对应的购买方案,代码略
If maxje >0 Then List1.AddItem "剩余金额:" & CStr(n - maxje) & " 总喜爱度:" & CStr(maxzxa)
Else
List1.AddItem "钱太少"
End if
End Sub
图b |