汇编x86程序.计算输入中的数字 [英] Assembly x86 program. Counting numbers in an input
问题描述
你好,我只是在学习汇编语言,所以我还不太了解.
Hello I am just learning assembly so I don't really understand many things yet.
我必须编写一个程序,用户在其中输入各种字母数字等的某种行.该程序应计算输入中有多少个数字并打印出计数器.
I have to write a program where the user inputs some kind of line of various letters numbers etc. And the program should count how many numbers there are in the input and print the counter out.
这是我的代码:
.model small
.stack 100h
.data
buffer db 100, ?, 100 dup (0)
count db 0
.code
start:
mov ax, @data
mov ds, ax
mov dx, offset buffer
mov ah, 0Ah
int 21h
mov ah, buffer
xor si, si
xor cx, cx
.loop:
.notdigit:
mov dl, buffer[si]
inc Si
cmp dl, 0
jz .end
cmp dl, '0'
jb .notdigit
cmp dl, '9'
ja .notdigit
inc count
jmp .loop
.end:
; count contains the digit count
mov dl, count
mov ah, 2h
int 21h
我没有收到任何错误,但是运行该程序后,它实际上无法正常工作.
I get no errors but the program doesn't really work when I run it.
这是怎么了?那我应该怎么改变呢?
What is wrong here? And how should I change it?
推荐答案
输入
buffer db 100, ?, 100 dup (0)
这是DOS函数0Ah使用的输入缓冲区的正确定义,但稍后,当您要遍历实际的输入字符串时,您需要跳过前2个字节,因为这些不是实际输入文本的一部分!
您可以将xor si, si
更改为mov si, 2
.
This is the correct definition for an input buffer to be used by DOS's functions 0Ah, but later on when you want to traverse the actual input string, you need to skip the first 2 bytes since these are not part of the actual inputted text!
You can change xor si, si
into mov si, 2
.
cmp dl, 0
jz .end
DOS为您提供的输入以回车符(ASCII 13)终止,因此测试零是没有用的.
The input that DOS delivers you is terminated by a carriage return (ASCII 13) and so it is useless to test for a zero.
下面的代码使用AL
而不是DL
,因为生成的汇编代码会短一些.
存在替代解决方案,但这是最接近您的解决方案:
Below code uses AL
instead of DL
because the resulting assembly code will be a bit shorter.
Alternative solutions exist but this one is closest to what you got:
mov si, 2
.loop:
mov al, buffer[si]
inc si
cmp al, 13
je .end
cmp al, '0'
jb .loop ;notdigit
cmp al, '9'
ja .loop ;notdigit
inc count
jmp .loop
.end:
输出
mov dl, count
mov ah, 2h
int 21h
此DOS功能要求DL
中的字符.您的 count 变量只是一个数字,很可能是一个很小的数字!
通过添加48,您可以轻松地将0到9的小数字转换为它们各自的字符.
This DOS function expects a character in DL
. Your count variable is just a number, most probably a very small number!
You can easily convert the small numbers from 0 to 9 into their respective characters by adding 48.
mov dl, count
add dl, '0' ;ASCII code for '0' is 48
mov ah, 02h
int 21h
这篇关于汇编x86程序.计算输入中的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!