0

I am trying to take an average of user given scores. In trying to get it to work, I realized it wasn't adding the scores given correctly. It seems like ax is always giving me the same value (47224) and adding the score to it, and then resetting to that value (47224) again. I've tried mov ax, 0; and it does the same thing. bx increments exactly like it is supposed to. What am I doing wrong?

#include <iostream>

using namespace std;

short score, avg, total=0;

void displayText() {
    cout << "Let's compute your score's average:  " << endl;
}

void readScore() {
    cout << "Enter your score (-1) to stop: ";
    cin >> score;
}

int main() {

    _asm {
        call displayText;  //function that asks for scores
        mov ax, total;  //total of scores
        mov bx, 0; //counter of scores

    WhileLoop:
        call readScore;  //asks user for one score

        cmp score, -1;  //compare score to -1
        je ExitLoop;   //if -1, exit loop

        add ax, score;   //add score to the running total
        inc bx;          //inc the counter
        jmp WhileLoop;     //jump to start of loop

    ExitLoop:
        //cwd;
        //idiv bx;   //divide the total by the count of scores

        mov avg, ax;
    }

    cout << "Average Score: " << avg << endl;

    return 0;

}
'''
Jenni
  • 1
  • 1
  • It would be helpful to know the function `readScore`. So that we can know if it's overwriting `AX` or `BX`. You also do not change the variable `score` in your loop - you just add its value to `AX` - which maybe doesn't change anything of relevance. So `score` stays the same. – zx485 Feb 10 '20 at 00:37
  • I eddied the code to show the entire thing. I'm pretty sure score is changing when I debug. – Jenni Feb 10 '20 at 00:50
  • I strongly suspect that `readScore` modifies `ax`. You'll need to look up the calling conventions for your compiler and see which registers are allowed to be modified by functions. – Nate Eldredge Feb 10 '20 at 01:06
  • 1
    Thx for updating your code. Now we can see that `score` is updated via `cin`. But it is also probable that `AX` is overwritten (due to the calling convention). Try changing its occurrences to `SI`or `DI` which are usually not overwritten. – zx485 Feb 10 '20 at 01:07
  • I changed it to SI and it worked! Now I just have to get the division part and I'm good! Thanks so much. – Jenni Feb 10 '20 at 01:28
  • What compiler are you using? Is it really an old 16-bit compiler like OpenWatcom or Borland, or are you just using 16-bit operand-size in a program built with modern MSVC++? – Peter Cordes Feb 10 '20 at 04:11

0 Answers0