我正在编写一个 QBasic 程序,该程序将使用 DO TILL 循环接收 10 名学生的分数并计算最低分数,但是当我运行它并输入 10 名学生分数时,我的程序似乎总是冻结。
我尝试了我所知道的一切,但它仍然冻结。
下面是我的代码:
DIM arr(10) AS INTEGER
DIM low AS INTEGER
DIM x AS INTEGER
CLS
x = 0
DO UNTIL x >= 10
INPUT "Enter Number: ", arr(x)
x = x + 1
LOOP
low = arr(1)
DO UNTIL x >= 11
IF arr(x) < low THEN
low = arr(x)
END IF
LOOP
CLS
PRINT "All Marks Are:"
PRINT arr(x); " ";
PRINT
PRINT "The Lowest Number is: "; low
我期待以下结果:
All Marks Are:
54 32 59 43 90 43 12 4 54 35
The Lowest Number is: 4
好的,我会改变你的代码中的几件事。 首先
DO UNTIL x >= 10
INPUT "Enter Number: ", arr(x)
x = x + 1
LOOP
为什么要使用做...在这里循环? 我会选择一个 FOR 循环:
FOR x = 1 to 10
INPUT "Enter Number: ", arr(x)
NEXT
它更传统,代码更短,整体更干净。
其次,你的第二个做...LOOP无法退出。 是的,当然,当 x 大于或等于 11 时它会退出,但什么时候会发生? 在你的循环中没有重新定义x,所以你的循环要么是无限的(如果x开始小于11),要么是无意义的(如果x已经是11或更大)。 在这种情况下,此时 x 将等于 10,因此您的代码将如您所描述的那样冻结。
不幸的是,您尝试执行的解析在 QBasic 中过于复杂,但这是可能的。为清楚起见,在程序的顶部定义TRUE
和FALSE
:
CONST TRUE = 1
CONST FALSE = 0
然后,当您来到要解析最小值的位置时,请执行以下操作:
finished% = TRUE 'I start by defining as TRUE and define as FALSE if I find
'a value which is smaller than the currently tested value.
CurTest% = 1 'This represents the array element which I am currently testing.
'It will change only when the program finds a value smaller than
'the one it is currently testing.
DO
finished% = TRUE
FOR i = CurTest% + 1 TO 10
IF arr(i) < arr(CurTest%) THEN
finished% = FALSE
CurTest% = i
EXIT FOR
END IF
NEXT i
LOOP UNTIL finished% = TRUE
'The loop will only complete once it has gone through a complete FOR...NEXT
'without finding a smaller value.
PRINT "The smallest value is:"; arr(CurTest%)
*注意:代码未经测试;可能存在怪癖/错误。
希望这有帮助!
稍微修改代码以获得低分会导致:
DIM arr(10) AS INTEGER
DIM low AS INTEGER
DIM x AS INTEGER
CLS
x = 1
DO UNTIL x > 10
INPUT "Enter Number: ", arr(x)
x = x + 1
LOOP
low = arr(1)
x = 1
DO UNTIL x > 10
IF arr(x) < low THEN
low = arr(x)
END IF
x = x + 1
LOOP
CLS
PRINT "All Marks Are:"
FOR x = 1 TO 10
PRINT arr(x); " ";
NEXT
PRINT
PRINT "The Lowest Number is: "; low
您可能希望在第二次循环之前将x
设置回 0(或使用其他变量)。因为它将继续从您在第一个循环中中断的地方递x
。
它也可能会遇到第 2 个循环的问题,因为您的数组只占用 10 个整数,但您正在尝试访问数组中的第 11 个位置。
确定 10 项最低分数的更有效方法:
REM determine lowest score of 10 items
CLS
FOR x = 1 TO 10
PRINT "Enter Number"; x;: INPUT arr(x)
IF x = 1 THEN low = arr(x)
IF arr(x) < low THEN
low = arr(x)
END IF
NEXT
PRINT "All Marks Are:"
FOR x = 1 TO 10
PRINT arr(x); " ";
NEXT
PRINT
PRINT "The Lowest Number is: "; low
另一个样本,用于确定任意数量项目的最高/最低/平均分数:
REM determine highest/lowest/average score of any number of items
CLS
PRINT "Number of items";: INPUT n
DIM arr(n) AS SINGLE
FOR x = 1 TO n
PRINT "Enter Number"; x;: INPUT arr(x)
IF x = 1 THEN low = arr(x): high = arr(x)
avg = avg + arr(x)
IF arr(x) < low THEN
low = arr(x)
END IF
IF arr(x) > high THEN
high = arr(x)
END IF
NEXT
PRINT "All Marks Are:"
FOR x = 1 TO n
PRINT arr(x);
NEXT
PRINT
PRINT "The Highest Number is:"; high
PRINT "The Lowest Number is:"; low
PRINT "The Average of all Scores is:"; avg / n