尝试在装配体中打印星形三角形

时间:2019-10-11 05:33:52

标签: assembly nasm

section .data
        star db '*'
        num db '1'
        endl db 10
        line db '1'
    section .text
     global _start

    _start:

    Star:
        mov edx,1           ;using 1 byte as appropriate
        mov ecx,star        ;;moving num into ecx to print the star
        mov ebx,1           ;;_STDOUT
        mov eax,4           ;;SYS_WRITE
        int 80h

         inc byte [num];num= 2

        mov al, [line];al=1
        mov bl, [num];bl=1
        cmp al,bl
        je Star;always false



        jmp PrintLine
      ;loop

    PrintLine:

        mov edx,1;using 1 byte as appropriate
        mov ecx,endl ;;moving num into ecx to print the star
        mov ebx,1  ;;_STDOUT
        mov eax,4  ;;SYS_WRITE
        int 80h

        inc byte [line] ;2
        cmp byte[line] , '9' ;comparing 2 to 9

        jl Star

    end:
    mov eax,1 ; The system call for exit (sys_exit)
    mov ebx,0 ; Exit with return code of 0 (no error)
    int 80h;

此代码的结果仅是9行中的单颗星,但是我不知道如何随着行数的增加来增加星数。请帮忙。我使用了两个循环,其中一个循环位于另一个循环内。如果跳跃失败或通过,则递增。一个循环用于打印星星,另一个循环用于打印下一行。我已经写了很多遍逻辑,从逻辑上讲似乎可行,但是我无法弄清楚语法和代码的位置

1 个答案:

答案 0 :(得分:1)

我喜欢将每个部分分成几个步骤。首先,我不会使用内存作为变量。正如Peter所指出的,esiedi仍然可用。

_start:

    mov esi, 0 ; line counter
    mov edi, 0 ; star counter

基本上,主要的循环任务是检查是否到达9行,然后退出。如果不是,我们需要打印一些星星:

main_loop:

    inc esi
    cmp esi, 9
    jg end ; have we hit 9 lines?

    ; print 1 whole line of stars
    call print_line

    jmp main_loop

现在我们需要实际打印一行星星:

print_line:

    mov edi, 0; we've printed no stars yet, this is a new line

printline_loop:

    call print_star ; print a single star character
    inc edi ; increment the number of stars we've printed
    ; have we printed the same number of stars as we have lines?
    cmp edi, esi
    jne printline_loop
    call print_eol

    ret

最后,要打印星号或换行符的单个子程序的最后一组:

print_star:

    mov edx, 1
    mov ecx, star
    mov ebx, 1
    mov eax, 4
    int 80h

    ret

print_eol:

    mov edx, 1
    mov ecx, endl
    mov ebx, 1
    mov eax, 4
    int 80h

    ret

end:

    mov eax, 1
    mov ebx, 0
    int 80h

Here it is running at IDEOne

输出:

*
**
***
****
*****
******
*******
********
*********