我正在编写一个QBasic程序,该程序将使用DO UNTIL循环接收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
答案 0 :(得分:1)
好的,我会在您的代码中更改几件事。首先,
DO UNTIL x >= 10
INPUT "Enter Number: ", arr(x)
x = x + 1
LOOP
为什么在这里使用DO ... LOOP?我会选择一个FOR循环:
FOR x = 1 to 10
INPUT "Enter Number: ", arr(x)
NEXT
这是更常规,更短的代码和更简洁的代码。
第二,您的第二个DO ... 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%)
* N.B .:代码未经测试;可能会有怪癖/错误。
希望这会有所帮助!
答案 1 :(得分:1)
稍微修改代码以获得较低的分数会导致以下结果:
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
答案 2 :(得分:0)
您可能希望在第二个循环之前将x
设置回0(或使用其他变量)。因为它将继续从您在第一个循环中停下来的位置开始递增x
。
第二个循环也可能会遇到问题,因为您的数组仅包含10个整数,但是您试图访问数组中的第11个位置。
答案 3 :(得分:0)
确定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
答案 4 :(得分:0)
确定任意数量项目的最高/最低/平均分数的另一个样本:
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