如何修改LMC程序实现任意输入三个数字从大到小正确输出
LMC 三个数任意输入降序排序修改方案
原代码问题
你当前的代码仅做了碎片化的分支比较,没有完整覆盖三个数的两两排序流程,也没有做标准的变量交换逻辑,仅能匹配输入刚好为升序的特殊场景;且比较过程中直接修改third变量值,会丢失原始输入数据,导致其他输入场景下排序结果错误。
实现逻辑
要实现任意三个数的降序排序,通过三次两两比较+交换即可完成:
- 比较
first和second,如果second更大则交换两者,保证first ≥ second - 比较
second和third,如果third更大则交换两者,保证second ≥ third - 再次比较
first和second,避免上一步交换second后出现first < second的情况,再次保证first ≥ second - 依次输出
first、second、third即可得到从大到小的结果
修改后完整代码
INP STA first // 存储第一个输入值 INP STA second // 存储第二个输入值 INP STA third // 存储第三个输入值 // 第一步:保证first >= second step1 LDA second SUB first BRP swap1 // second >= first时需要交换 BRA step2 // 否则直接进入下一步 swap1 LDA first STA temp LDA second STA first LDA temp STA second // 第二步:保证second >= third step2 LDA third SUB second BRP swap2 // third >= second时需要交换 BRA step3 // 否则直接进入下一步 swap2 LDA second STA temp LDA third STA second LDA temp STA third // 第三步:再次保证first >= second step3 LDA second SUB first BRP swap3 // second >= first时需要交换 BRA output // 否则直接输出 swap3 LDA first STA temp LDA second STA first LDA temp STA second // 按从大到小顺序输出 output LDA first OUT LDA second OUT LDA third OUT HLT first DAT second DAT third DAT temp DAT // 新增临时变量用于交换数值
内容的提问来源于stack exchange,提问作者user17107474
相关产品推荐
相关产品推荐

