Search code examples
visual-c++assemblyx86masminline-assembly

Calculating average in assembly


I have a program to take user input (as many as the user wants to enter) and calculate the average in assembly. Even with clearing the registers by using xor and mov eax,0; I cannot get the number to come out right. Thanks for any help in advance!

Sample I/O:

70 
88 
90 
77 
-1

The answer I get is always a VERY high number

#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;
}

Solution

  • You try to keep the total in eax but that's clobbered by the pnt and gtsc functions. You might want to add to total instead, and load that before the division. For example:

    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: learn to use a debugger.