计算装配平均值

Calculating average in assembly

我有一个程序可以接受用户输入(用户想输入多少就输入多少)并计算汇编中的平均值。即使使用 xor 和 mov eax,0 清除寄存器;我无法得到正确的数字。提前感谢您的帮助!

样本I/O:

70 
88 
90 
77 
-1

我得到的答案总是很高

#include <iostream>
using namespace std;
int score = 0, avg = 0, total=0, counter = 0;

void pnt()
{
cout << "Enter your score (-1) to stop: ";
}
void gtsc()
{
cin >> score;
}
void pnt_test()
{
cout << total << endl;
}

int main()
{

cout << "Let's compute your average score:" << endl;

__asm
{

    xor eax, eax
    xor edx, edx
    fn:
    call pnt
        call gtsc
        cmp score, -1
            je stop
            jne add_1
    add_1: 
        add eax, score
        inc counter
        jmp fn
    stop: 
        cdq
        mov total, eax
        idiv counter
        mov avg, eax
        call pnt_test
}

cout << "Your average is " << avg << endl;
system("pause");
return 0;
}

您尝试将总计保持在 eax 中,但这被 pntgtsc 函数破坏了。您可能想改为添加 total ,并在除法之前加载它。例如:

fn:
call pnt
    call gtsc
    cmp score, -1
        je stop
        jne add_1
add_1: 
    mov eax, score
    add total, eax
    inc counter
    jmp fn
stop: 
    mov eax, total
    cdq
    idiv counter
    mov avg, eax
    call pnt_test

PS: 学习使用调试器。