vb exam救命 有冇vb高手可以救救我呀 急問 (swap, write to txt file ...)

2007-06-04 5:13 pm
我下個禮拜考試,但有D野唔識做

1.唔識計個average
2.試左好多次都Swap唔倒D data (靜係擺在第一欄先得,但係我想擺最尾)
3.如果要寫番入去個text file 要點寫??


my program(vb6)
http://uwants.com/attachment.php?aid=2313317

回答 (1)

2007-06-06 7:06 am
✔ 最佳答案
一個錯誤是太早將檔案數據放進 listbox,而不放進記憶體,即變數內,因此數據不能作計算使用.
另一錯誤是 sorting 的程序設計(algorithm),請參考下面的範例和 bubble sort 的程式.

Option Explicit

Private Type Student_Score ' 使用者界定的數據型式 (user defined type)
ID As String
LastName As String
FirstName As String
Score As Long
End Type

Private Sub Command1_Click()
Dim temp As String, Record_Count As Long, i As Long
Dim Total_Score As Long, High_Score As Long, Low_Score As Long
Dim Average_Score As Double
Dim StudentArray() As Student_Score ' 宣告一個動態的列陣 (dynamic array)

Record_Count = 0
Open "CIC_Current_List.txt" For Input As #1
Do While Not EOF(1) ' 找出數據的數量
Line Input #1, temp
Record_Count = Record_Count + 1
Loop
Close #1

ReDim StudentArray( Record_Count - 1 ) ' 按數據的數量重新宣告列陣的多少

i = 0
Open "CIC_Current_List.txt" For Input As #1
Do While Not EOF(1)
' 把數據讀進列陣
Input #1, StudentArray(i).ID, StudentArray(i).LastName, StudentArray(i).FirstName, StudentArray(i).Score
i = i + 1
Loop
Close #1

Bubble_Sort_Ascending StudentArray

Open "CIC_Current_List_Output.txt" For Output As #1
For i = 0 To UBound(StudentArray)
Total_Score = Total_Score + StudentArray(i).Score

' 將列陣的數據放進 listbox
pLBName.AddItem "Score:&;quot; & StudentArray(i).Score & " ,ID:" & StudentArray(i).ID & " ,First Name:" & StudentArray(i).FirstName & " ,Last Name:" & StudentArray(i).LastName

' 寫入 text file
Print #1, StudentArray(i).ID & ", " & StudentArray(i).LastName & ", " & StudentArray(i).FirstName & ", " & StudentArray(i).Score
Next
Close #1

Average_Score = Total_Score / Record_Count
Hign_Score = StudentArray( Record_Count - 1 ).Score
Low_Score = StudentArray(0).Score
End Sub

Private Sub Bubble_Sort_Ascending(ByRef Array1() As Student_Score)
Dim Array_Bound As Long, i As Long, j As Long
Dim temp As Student_Score

Array_Bound = UBound( Array1 )
For i = 0 To Array_Bound - 1
For j = 0 To Array_Bound - i - 1
If Array1( j ).Score > Array1( j + 1 ).Score Then
temp = Array1 ( j + 1 )
Array1( j + 1 ) = Array1( j )
Array1( j ) = temp
End If
Next
Next
End Sub


收錄日期: 2021-04-25 20:33:50
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20070604000051KK00752

檢視 Wayback Machine 備份