【问题标题】:Print triangle of numbers in assembly x86在汇编x86中打印数字三角形
【发布时间】:2017-01-19 13:54:13
【问题描述】:

我必须在 tasm 中执行一个程序,该程序必须在数字上打印一个三角形,如下所示:

input: n.  Ex: n=4

output:

1
1 2
1 2 3 
1 2 3 4

我已经设法让我的程序打印这个东西,但我还必须让它处理 0 到 255 之间的数字,而不仅仅是数字。

我知道我必须逐位读取数字并创建这样的总和:

如果我必须读82,我先读8,把它放在一个寄存器里,然后,当我读2的时候,它必须加到8*10。

你能帮我在我的程序中实现这个吗?

.model small
.stack 100h

.data
    msg db "Enter the desired value: $", 10, 13
    nr db ?

.code
    mov AX, @data
    mov DS, AX

    mov dl, 10
    mov ah, 02h
    int 21h
    mov dl, 13
    mov ah, 02h
    int 21h

    mov DX, OFFSET msg
    mov AH, 9
    int 21h
    xor ax, ax

    mov ah, 08h                 ;citire prima cifra din numar
  int 21h


  mov ah, 02h   
  mov dl, al
  int 21h   

 sub al,30h  
  mov ah,10
  mul ah                

  mov [nr],al         ;mutam prima cifra inmultita cu 10 in nr

  mov ah, 08h 
  int 21h   



  mov ah, 02h         
  mov dl, al
  int 21h

  sub al, 30h         
  add [nr], al 


    sub nr,30h

    mov dl, 10
    mov ah, 02h
    int 21h
    mov dl, 13
    mov ah, 02h
    int 21h

    mov cx,1

    mov bx,31h
    mov ah, 2
    mov dx, bx
    int 21h 

loop1:
    xor ax, ax
    mov al, nr
    cmp ax, cx
    je final

    mov dl, 10
    mov ah, 02h
    int 21h
    mov dl, 13
    mov ah, 02h
    int 21h

    mov bx, 0             

loop2:  
    inc bx               
    add bx,30h
    mov ah, 2
    mov dx, bx
    int 21h 
    sub bx,30h
    cmp bx, cx           
    jne loop2

    inc bx               
    add bx,30h
    mov ah, 2
    mov dx, bx
    int 21h 

    inc cx
    jmp loop1

final:
    mov AH,4Ch   ; Function to exit
    mov AL,00    ; Return 00
    int 21h

end

【问题讨论】:

  • 既然你知道你需要做x*10+y是什么导致你的问题?你不能这样做吗?这是微不足道的,但即使在 SO 上也有很多例子。
  • 因为你会做很多数字->ascii转换,你可以考虑优化。首先在内存缓冲区中绘制最后一行,然后为每一行修补它以仅显示所需数量的数字,并仅打印缓冲区,不再进行任何数字数学运算。实际上,即使不使用数字,也可以生成最后一行的初始打印,只需修补 ASCII 字符串。
  • 我在上面编辑了我的代码。我设法读取了一个两位数,但现在我不知道如何打印它们。此代码打印所有 ASCII 字符,我看不到逻辑。

标签: assembly x86 tasm


【解决方案1】:

你已经完成了一半。

"如果我必须读82,我先读8,把它存入寄存器,然后,当我读2时,必须加到8*10"

对于您读入的每个数字,您必须将前一个值乘以 10。不仅是第二个,第三个也是如此(您可以对第一个执行此操作,因为读取的值为 0)

剩下的是:

  result = 0
  while (more digits to come)
      result *= 10;
      result += value of current digit

这样做,
82 将是 ((0*10 + 8) + 2) = 82
251 将是 (((0*10 + 2) *10 + 5) *10 +1 = 251

与在循环中输出数字相同,对于 > 9 的值,您不能简单地添加 '0' 并打印 ascii 值,您必须将其编码为 ascii 字符串,并显示整个字符串(就像您已经做过的那样INT 21H/09H)

也帮自己一个忙,分清这些问题。编写“decode_bin”和“encode_bin”子函数,并将循环中的 INT 替换为对该函数的调用,否则 2 周左右后您将无法阅读它:-)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多