汇编——从一道题目浅谈分支结构

浅谈分支结构

程序的分支结构是非常常见的,本文将通过一道题浅谈汇编里的分支结构。

题目

  1. 程序执行是,显示提示信息“Please input a string (length<9):”,由用户输入一个长度小于9的字符串;
  2. 然后显示提示信息“Please input the index of the char to display”,请用户指定该串中的某个字符串的位置号,程序控制用户输入的位置号必须合法;若不合法则程序退出
  3. 程序将用户指定位置的字符串显示出来

输出样例一

Please input a string (length < 9):ABCDEFG
Please input the index of the char to display :2
The char is:C

输出样例二

Please input a string (length < 9):ABC
Please input the index of the char to display :4
The index is invalid!

代码

先上整体代码

data SEGMENT
    strmess db 'Please input a string(length < 9):$'
    strtoolong db 0ah,0dh,'The string is too long!$'
    nummess db 0ah,0dh,'Please input the number(index < 4) of the char to display:$'
    charmess db 0ah,0dh,'the char is :$'
    chartoolong db 0ah,0dh,'The index is invaild!$'
    buf db 10,?,10 dup(0)
    num db ?
data ENDS
;description
code SEGMENT USE16
    assume cs:code,ds:data
    start:mov ax,data
          mov ds,ax
          lea dx,strmess
          mov ah,09h
          int 21h

          lea dx,buf
          mov ah,0ah
          int 21h

          cmp buf+1,8          
          jg strlong
          jle strnext
    strlong:
          lea dx,strtoolong
          mov ah,09h
          int 21h
          
          mov ax,4c00h
          int 21h
        
    strnext:
          lea dx,nummess
          mov ah,09h
          int 21h

          mov ah,01h
          int 21h

          sub al,30h
          mov num,al
          cmp buf+1,al
          jle charlong
          jg charnext
    charlong:
          lea dx,chartoolong
          mov ah,09h
          int 21h
          
          mov ax,4c00h
          int 21h
    charnext:
          lea dx,charmess
          mov ah,09h
          int 21h

          mov bl,num
          mov bh,0
          mov dl,buf[bx+2]
          mov ah,02h
          int 21h

          mov ax,4c00h
          int 21h
code ENDS
END start
  • 运行结果
    test.exe运行结果

分析

这个题目首先需要利用10号调用获取用户输入,在通过判断字符串是否超过8来进行一个跳转分支,如果超过8,则输出错误信息并结束程序,正确则继续执行。

  • 通过cmp来比较返回一个值,再利用jump来实现跳转
  • sub al,30h之所以al需要减30h,是因为1号调用接受的是用户输入字符的ASCII码,而0~9的整形与其ASCII码正好相差30.

分支结构

Created with Raphaël 2.2.0 开始 我的操作 跳转命令 结束 yes no

几个跳转指令的例子

指令同义跳转条件
jejz相等
jgjnle大于
jljnge小于

总结

这个程序还可以加入loop循环,使用户输入不合法时,继续执行直到输入正确。汇编菜鸟一个,如有错误或者更好的方法可以在评论区指出,欢迎大家一起讨论。

  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值