为什么这段MARIE代码在循环变量达到10时无法终止循环?
MARIE程序循环终止问题修复
问题分析
你的程序存在两个核心问题导致无法终止循环且迭代次数错误:
- 循环终止条件判断错误:MARIE的
SKIPCOND 000指令是当累加器(AC)的值小于0时跳过下一条指令。你当前用它判断X == 11,但X=11时AC=11>0,不会跳过JUMP LOOP,导致无限循环。 - 计数器初始值错误:你将Counter初始化为1,而实际需要统计输出数字的次数(输入7时输出4次),初始值应为0,每次输出后递增才能得到正确次数。
修正后的代码
ORG 400 / Start at address 400 INPUT / Take a number from the user STORE X / Store INPUT in memory location X LOAD ZERO / Load the constant value 0 STORE Counter / Initialize Counter to 0 LOOP, LOAD X / Load the value of X OUTPUT / Display the current value of X LOAD Counter / Load the current counter value ADD ONE / Increment the counter by 1 STORE Counter / Store the updated counter value ADD ONE / Increment X by 1 STORE X / Store the new value of X LOAD X / Load the value of X SUBTRACT 10 / Calculate X - 10 SKIPCOND 800 / Skip next instruction if X > 10 (AC > 0) JUMP LOOP / Jump back to the start of the loop LOAD Counter / Load the final counter value OUTPUT / Display the counter HALT / Terminate the program X, DEC 0 / Memory location for X (initialized to 0) Counter, DEC 0 / Memory location for Counter (initialized to 0) ONE, DEC 1 / Constant value 1 ZERO, DEC 0 / Constant value 0
关键修正说明
- 循环终止逻辑:通过
SUBTRACT 10计算X与10的差值,使用SKIPCOND 800(当AC>0即X>10时跳过跳转指令),确保X超过10时立即退出循环。 - 计数器初始化:将Counter初始值设为0,每次输出后递增,保证统计的次数与输出数字的数量一致(输入7时,输出4次后Counter值为4)。
内容的提问来源于stack exchange,提问作者ZiwaseemiZ
相关产品推荐
相关产品推荐

