有n個同學(n為偶數),兩人一組,共分成 n/2組。令n/2個同學之體重總和為{S1,S2,……Sn},m為體重總和之平均值m=[(S1,S2,……Sn )/n],分組的原則為必須使得m|之差距總合為最小。(輸出結果的差距若非為最小,則本題算錯,零分計算。)寫一程式完成此分組工作。
輸入說明:第一列為學生人數n,(4≦n≦20)。
第二列到第n+1列為學生的體重。(30≦學生的體重≦150)
輸入範例:假定有10個同學,其體重分別為:82、53、74、84、45、46、57、67、43、47。實際輸入之檔案內容如下:
實際輸入:(test4.txt)
10
82
53
74
84
45
46
57
67
43
47
輸出說明:列印出每組同學之體重總和及個別體重,且必須依體重總和由大而小印出。
輸出範例:上例中的10個同學體重分別為:82、53、74、84、45、46、57、67、43、47。其各組體重總和及個別體重的實際輸出之檔案內容如下:
實際輸出:(result4.txt)
127 = 43 + 84
127 = 45 + 82
120 = 46 + 74
114 = 47 + 67
110 = 53 + 57
Dim N(21), W(151), M As Integer
回覆刪除Private Sub Form_Load()
Open App.Path & "/in.txt" For Input As #1
Open App.Path & "/out.txt" For Output As #2
Input #1, M
For i = 1 To M
Input #1, N(i)
Next i
For i = 1 To M
For j = 1 To M
If N(i) > N(j) Then a = N(i): N(i) = N(j): N(j) = a
Next j
Next i
For i = 1 To M / 2
Print #2, N(i) + N(M - i + 1) & " = " & N(M - i + 1) & " + " & N(i)
Next i
Close #2
Close #1
End Sub
Dim aa(50) As Integer
回覆刪除Dim bb(50) As String
Private Sub Form_Load()
Open App.Path & "\in.txt" For Input As #1
Open App.Path & "\out.txt" For Output As #2
Input #1, aaa
For i = 1 To aaa
Input #1, aa(i)
Next i
For i = 1 To aaa - 1
For j = i To aaa
If aa(i) > aa(j) Then Call cha(aa(i), aa(j))
Next j
Next i
For i = 1 To aaa \ 2
bb(i) = aa(i) + aa(aaa - i + 1) & " = " & aa(i) & " + " & aa(aaa - i)
Print #2, bb(i)
Next i
Close #1
Close #2
End Sub
Public Sub cha(a, b)
c = a
a = b
b = c
End Sub
剛剛沒注意到
回覆刪除有一個地方錯了
bb(i) = aa(i) + aa(aaa - i + 1) & " = " & aa(i) & " + " & aa(aaa - i)
這段應該要改成
bb(i) = aa(i) + aa(aaa - i + 1) & " = " & aa(i) & " + " & aa(aaa - i + 1)
才對
Private Sub Form_Load()
回覆刪除Dim num(20) As Integer
Open App.Path & "/in.txt" For Input As #1
Open App.Path & "/out.txt" For Output As #2
Input #1, x
For i = 1 To x
Input #1, a
num(i) = a
Next i
For i = 1 To x - 1
For j = i To x
If num(i) > num(j) Then
step = num(i)
num(i) = num(j)
num(j) = step
End If
Next j
Next i
For i = 1 To x / 2
ans = num(i) + num(x - i + 1)
Print #2, ans; "="; num(i); "+"; num(x - i + 1)
Next i
Close #2
Close #1
End Sub
高仔、小白、阿揚好,
回覆刪除你們的程式,都一樣,沒問題。
只是,題目中的那一行
「 分組的原則為必須使得m|之差距總合為最小。」
是什麼意思呢?
哦,且不說那句看不懂的話。
回覆刪除你們還少排了一次,結果的總和。
因為如果有4人,最重和最輕的兩人的和,和中間兩人的體動的和,一定是誰大嗎?
例如4人體重為:30 70 80 90
Dim stu(20) As Integer
回覆刪除Private Sub Form_Load()
Open App.Path & "\in.txt" For Input As #1
Open App.Path & "\out.txt" For Output As #2
Input #1, n
For i = 1 To n
Input #1, stu(i)
Next i
For i = 1 To n
For j = i To n
If stu(i) > stu(j) Then
Call change(stu(i), stu(j))
End If
Next j
Next i
For i = 1 To n / 2
Print #2, stu(i) + stu(11 - i) & " = " & stu(i) & " + " & stu(11 - i)
Next i
Close #2
Close #1
End Sub
Public Sub change(a, b)
c = a
a = b
b = c
End Sub
阿瑋好,
回覆刪除同樣的錯。自己改。