2

所以我对 QB64 并不太熟悉,而且文档很少,所以我遇到了麻烦。

TYPE character
FName AS STRING * 12
LName AS STRING * 12
ID_Num AS INTEGER
Year AS STRING * 2
GPA AS DOUBLE
END TYPE
DIM LENGTH AS INTEGER

LENGTH = 11

REDIM chars(0) AS character

CLS

n$ = "names1.txt"

OPEN n$ FOR INPUT AS #1

k = -1

WHILE (NOT (EOF(1)))
k = k + 1

REDIM _PRESERVE chars(k) AS character
INPUT #1, chars(k).FName, chars(k).LName, chars(k).ID_Num, chars(k).Year, 
chars(k).GPA

WEND
CLOSE #1


CALL sortArray(chars(), LENGTH)

SUB sortArray (score() AS INTEGER, SIZE AS INTEGER)

DIM x AS INTEGER
DIM y AS INTEGER
DIM COMPS AS INTEGER

x = 0
y = 0
COMPS = SIZE - 1

WHILE y < COMPS
    x = 0
    WHILE x < COMPS
        IF score(x) > score(x + 1) THEN
            CALL swap2(score(), x)
        END IF
        x = x + 1
    WEND
    y = y + 1
    WEND

    END SUB



    SUB swap2 (score() AS INTEGER, x AS INTEGER) 
DIM temp AS INTEGER
temp = score(x + 1)
score(x + 1) = score(x)
score(x) = temp
END SUB

我在以下行收到错误 - “传递给子的数组类型不正确”:

CALL sortArray(chars(), LENGTH) 

我假设因为我在上面使用了 REDIM,所以 sub 没有正确处理它,但我不确定如何解决这个问题。最终,我试图将文件读入数组,对该数组进行排序,然后将其打印给用户。目前,我对如何对数组进行实际排序感到困惑。

任何帮助将不胜感激。谢谢!

4

2 回答 2

2

您正在传递chars()包含 type 元素的数组character,但您的子例程只接受包含 type 元素的数组INTEGER

您需要的是score() AS character(更好地命名为chars() AS character),并且您可以根据您想要的任何标准(例如IF score(x).GPA > score(x+1).GPA THEN ...)进行排序。此外,还有一个内置SWAP语句可以为您交换内容,因此无需编写您自己的语句(除非您应该这样做)。

于 2017-05-03T23:38:21.433 回答
0

这是您的代码(经过大量修改),其中:

1) UDT 已正确声明。2) redim 仅在 $dynamic 声明时有效。3)“冒泡排序”更短。

REM $DYNAMIC
TYPE character
    FName AS STRING * 12
    LName AS STRING * 12
    ID_Num AS INTEGER
    Year AS STRING * 2
    GPA AS DOUBLE
END TYPE
DIM chars(0) AS character
n$ = "names1.txt"
OPEN n$ FOR INPUT AS #1
WHILE NOT EOF(1)
    k = k + 1
    REDIM _PRESERVE chars(k) AS character
    INPUT #1, chars(k).FName, chars(k).LName, chars(k).ID_Num, chars(k).Year, chars(k).GPA
WEND
CLOSE #1
CALL SortArray(chars(), k)
END
SUB SortArray (score() AS character, SIZE AS INTEGER)
' bubble sort
FOR x = 1 TO SIZE
    FOR y = x + 1 TO SIZE
        IF score(x).GPA > score(y).GPA THEN
            SWAP score(x), score(y)
        END IF
    NEXT
NEXT
END SUB
于 2017-05-07T02:09:25.523 回答