2014-01-27 67 views
0

我以彙編開始,並試圖創建一個簡單的循環打印eax值,但它不起作用,我不完全確定我在這裏做什麼。程序集循環不打印值

global _main  ; make visible for linker 
extern _printf  ; link with printf 
; ------------------------------- 
section .const 
    hello db `Hello world! %d \n\0`; 0 on stringi lõpp. 
    arv dw 5 ; %d võimaldab stringis arvu näidata. 
    otsitav dw 10 ;10 on reavahetus 
    vastus dw 0 ;dw läheb arvule 
section .text 
; ------------------------------- 
_main: 
    mov eax, otsitav ; Annan eax-le kasutaja sisestatud väärtuse. 
    mov ebx, 1 ; Annab ebx-le väärtuse 1 - sealt alustab for tsükliga. 

    .loop1: 
    dec eax ; võtab eax-ilt ühe ära. 
    push eax 
    call _printf 
    add esp, 4 ; tasakaalustab. 
    cmp eax, 0 ; eax ? 0 
    je .loop1 ; kui ? asemele saab = panna siis hüppa .loop1 juurde 
    ret 
+2

'printf'需要一個格式字符串來解釋你給它的其餘參數。另外,不要指望'eax'在函數調用中保留它的值。 – Michael

回答

0

我不明白你的意見,所以我真的不知道發生了什麼,但我做了一個示例程序爲您使用bss節來存儲您的計數器;

global _main 
extern _printf 

[section] .bss 
    storage resd 1  ; reserve 1 dword 

[section] .data 
    fmt db "output = %s %d", 0dh,0ah,0 ; newline in formate now 

    hello db "hello world",0 ; the string 

    count equ 10    ; output ten times 

[section] .text 

_main: 
    push ebp 
    mov ebp, esp   ; stack related 

    mov eax, count 
    mov dword[storage], eax ; store eax's current value 

nLoop: 
    push eax   
    push hello 
    push fmt 
    call _printf 
    add esp, 12    ; clean 3 args (4 * 3) 

    mov eax, dword[storage] ; grab current count 
    sub eax, 1 
    mov dword[storage], eax ; store new value for later 
    jnz nLoop    ; test if value is zero 

    leave ; also stack related 
    ret 

輸出;

output = hello world 10 
output = hello world 9 
output = hello world 8 
output = hello world 7 
output = hello world 6 
output = hello world 5 
output = hello world 4 
output = hello world 3 
output = hello world 2 
output = hello world 1 
+1

無用的使用'cmp'。您可以通過簡單地使用'dec eax'製作的標誌來避免使用該指令,並將該跳轉改爲'jnz'。事實上,你不需要保存進位標誌,所以我不知道你爲什麼使用'dec eax'而不是 - 在這種情況下更快,儘管更大 - 'sub eax,1'。 –

+0

哦該死的,你的權利,最初我有一個'jnz',一個'sub',我甚至都不記得我的邏輯!謝謝你告訴我!!虐待改變它使用'sub'指令我註釋了沒有很好的理由:/ – James