简体   繁体   中英

Trying to sum numbers , but loop doesn't stop

Given the following code in Assembly:

.section .rodata

input_format:  .string  "%d"
output_format: .string  "%d\n"

    .text
    .globl  main
    .type   main,@function
main:
    pushl   %ebp
    movl    %esp,%ebp

    movl    $0,%ebx     # reset the sum register
    movl    $0,%esi     # reset the counter of the numbers
    movl    $0,%eax     # in order to know when to stop the loop
.loop:
    addl    $-8,%esp    # moving down the stack
    pushl   %esp
    pushl   $input_format
    call    scanf       # call scanf to get number from the user
    addl    $8,%esp
    addl    (%esp),%ebx # add the number to the total summary
    movl    (%esp),%ecx
    addl    $1,%esi     # add 1 to the counter
    pushl   $output_format
    call    printf      # print the given number
    cmpl    %ecx,%eax
    jne .loop

    # return from printf:
    movl    $0,%eax
    movl    %ebp,%esp
    popl    %ebp
    ret

I'm trying to sum numbers larger than 0 in ebx and eventually calculate their average, but from some reason the loop wouldn't stop when I put a "0" (0 is suppose to be the end of the loop) . Where did I go wrong?

Your loop terminates on comparison of ecx and eax. eax is set to 0, but ecx doesn't appear to hold a count down value. Also, are you sure that your functions are preserving your register values correctly?

Um, I bet that all your functions are modifying eax when they return - this is where return values are stored. Move your eax assignment of 0 (or '0' / $30) down to just before the compare. No need to set it until its needed anyways.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM