浅谈分支结构
程序的分支结构是非常常见的,本文将通过一道题浅谈汇编里的分支结构。
题目
- 程序执行是,显示提示信息“Please input a string (length<9):”,由用户输入一个长度小于9的字符串;
- 然后显示提示信息“Please input the index of the char to display”,请用户指定该串中的某个字符串的位置号,程序控制用户输入的位置号必须合法;若不合法则程序退出
- 程序将用户指定位置的字符串显示出来
输出样例一
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
- 运行结果
分析
这个题目首先需要利用10号调用获取用户输入,在通过判断字符串是否超过8来进行一个跳转分支,如果超过8,则输出错误信息并结束程序,正确则继续执行。
- 通过
cmp
来比较返回一个值,再利用jump
来实现跳转 sub al,30h
之所以al需要减30h,是因为1号调用接受的是用户输入字符的ASCII码,而0~9的整形与其ASCII码正好相差30.
分支结构
几个跳转指令的例子
指令 | 同义 | 跳转条件 |
---|---|---|
je | jz | 相等 |
jg | jnle | 大于 |
jl | jnge | 小于 |
总结
这个程序还可以加入loop循环,使用户输入不合法时,继续执行直到输入正确。汇编菜鸟一个,如有错误或者更好的方法可以在评论区指出,欢迎大家一起讨论。