-1

I'm currently doing a school project where I need to find an average rating of an array, while I'm not having a problem getting the average number if I try to get the average number again it is adding itself onto the previous average. ex: input

3 //this is to get the average rating to display from the menu

output

4

input

3

output

8

Here is my code to display the avg rating


void displayAverageRating(int ratings[NUM_PEOPLE]) {
  for (i = 0; i <= 835; i++) {
    sum += ratings[i];
    avgrating = sum / NUM_PEOPLE;
    if (i == 835) {
      cout << "The Average of the ratings for Star Wars: Episode I The Phantom "
              "Menace was ";
      cout << avgrating << "\n";
    }
  }
}

Here are my menu options

do {
    getMenu();
    cin >> Menu_Choice;
    switch (Menu_Choice) {
        case 1:
            displayRatings(ratings);
            break;
        case 2:
            ChangeARating(ratings);
            break;
        case 3:
            displayAverageRating(ratings);
            break;
    }
}
while (Menu_Choice !=4);

return 0;
cigien
  • 57,834
  • 11
  • 73
  • 112
North
  • 1
  • 3
  • If you don't want a running total over multiple calls of the function, you would have to set `sum` (back) to 0 somewhere. Are you doing that? Not in the code you have shown. –  Oct 17 '21 at 19:55
  • Please provide a [mre]. – Yunnosch Oct 17 '21 at 20:01
  • Your `sum` variable is global - it is declared outside the `displayAverageRating()` function. That is why it keeps its value over consecutive calls to the function. You should make it a local variable, and initialize it to 0 (`int sum { 0 };`). There is no reason any code outside the function should have access to it. – einpoklum Oct 17 '21 at 20:08
  • This doesn’t address the question, but the loop in `displayAverageRating` should just do the sum: `for (i = 0; i <= 835; i++) { sum += ratings[i]; }`. After that, calculate and display `avgrating`. – Pete Becker Oct 17 '21 at 20:30
  • I'm reopening this question, as the duplicate target was both too generic, and for the wrong language, and I see no particular reason this question should remain closed. – cigien Oct 19 '21 at 19:52

1 Answers1

1

You are not clearing your previous call sum value. Just reassign value:

void displayAverageRating(int ratings[NUM_PEOPLE])
{
  sum = 0;
  // the rest of your code
}
Adrian Kokot
  • 2,172
  • 2
  • 5
  • 18
  • I don't think that resetting `avgrating` helps. It is overwritten anyway. I look at `sum` and think it should be reset... Hard to tell of course, without a decent [mre]. – Yunnosch Oct 17 '21 at 20:00
  • @North If the answer solved your problem, you can go ahead and accept the answer. – cigien Oct 19 '21 at 19:54