计算机编程:信息学奥赛选拔试题小华有138元9角钱,准备全部购买铅笔,店里有8角,6角,5角,4角一支的铅笔4种,请编写一个程序,在8角一支的铅笔必须购买一支的前提下,使买的铅笔数量最多,而钱

来源:学生作业帮助网 编辑:六六作业网 时间:2024/12/25 20:52:47
计算机编程:信息学奥赛选拔试题小华有138元9角钱,准备全部购买铅笔,店里有8角,6角,5角,4角一支的铅笔4种,请编写一个程序,在8角一支的铅笔必须购买一支的前提下,使买的铅笔数量最多,而钱计算机编

计算机编程:信息学奥赛选拔试题小华有138元9角钱,准备全部购买铅笔,店里有8角,6角,5角,4角一支的铅笔4种,请编写一个程序,在8角一支的铅笔必须购买一支的前提下,使买的铅笔数量最多,而钱
计算机编程:信息学奥赛选拔试题
小华有138元9角钱,准备全部购买铅笔,店里有8角,6角,5角,4角一支的铅笔4种,请编写一个程序,在8角一支的铅笔必须购买一支的前提下,使买的铅笔数量最多,而钱又恰好用完.输出各种铅笔的数量.

计算机编程:信息学奥赛选拔试题小华有138元9角钱,准备全部购买铅笔,店里有8角,6角,5角,4角一支的铅笔4种,请编写一个程序,在8角一支的铅笔必须购买一支的前提下,使买的铅笔数量最多,而钱
c1 = 138 * 10 + 9
Dim n() As Long, s() As String, l As Long, lmax As Long, s_xinxi As String
l = 0
For i1 = 8 To c1 Step 8
For i2 = 0 To c1 Step 6
For i3 = 0 To c1 Step 5
For i4 = 0 To c1 Step 4
If i1 + i2 + i3 + i4 = c1 Then
ReDim Preserve n(l) '记录总数
ReDim Preserve s(l) '记录排列
n(l) = i1 \ 8 + i2 \ 6 + i3 \ 5 + i4 \ 4
s(l) = "8毛:" & i1 \ 8 & "只,6毛:" & i2 \ 6 & "只,5毛:" & i3 \ 5 & "只,4毛:" & i4 \ 4 & "只"
If n(l) > lmax Then lmax = n(l)
l = l + 1
End If
Next
Next
Form1.Caption = "排列数" & l & "---最多铅笔数" & lmax & "----计算进度" & Format(i1 * 100 / c1, "00.0") & "%"
DoEvents
Next
Next
s_xinxi = ""
For i = 0 To lmax - 1
If n(i) = lmax Then
s_xinxi = s_xinxi & s(i) & vbCrLf
End If
Next
MsgBox s_xinxi
'优化代码
c1 = 138 * 10 + 9 '钱数随便写 单位毛
Dim s() As String, l As Long, lmax As Long, s_xinxi As String
l = 0
lmax = (c1 - 8) \ 4 + 1
For i1 = 8 To c1 Step 8
For i2 = 0 To c1 Step 6
For i3 = 0 To c1 Step 5
i4 = c1 - i1 - i2 - i3
If i4 Mod 4 = 0 Then
If i1 + i2 + i3 + i4 = c1 And i1 \ 8 + i2 \ 6 + i3 \ 5 + i4 \ 4 = lmax Then
ReDim Preserve s(l) '记录排列
s(l) = "8毛:" & i1 \ 8 & "只,6毛:" & i2 \ 6 & "只,5毛:" & i3 \ 5 & "只,4毛:" & i4 \ 4 & "只"
l = l + 1
End If
End If
If i1 \ 8 + i2 \ 6 + i3 \ 5 + (c1 - i1 - i2 - i3) \ 4 < lmax Then Exit For
Next
If i1 \ 8 + i2 \ 6 + (c1 - i1 - i2) \ 4 < lmax Then Exit For
Next
If i1 \ 8 + (c1 - i1) \ 4 < lmax Then Exit For
Next
s_xinxi = ""
For i = 0 To l - 1
s_xinxi = s_xinxi & s(i) & vbCrLf
Next
MsgBox s_xinxi