lowest value in league table

I'm having trouble with a program that creates a football league. The particular function I'm having trouble with is one which is supposed to display the team or teams with the best defense in the league ie.lowest goals against. I have the Get functions coded but the bestdefence is giving me trouble.

I can't seem to get it to just give me the team with the lowest goalsagainst. Instead it outputs each team with a lower value than is assigned to lowestgoalagainst

For example if I run it and lowestgoalagainst is set to equal a team with 3 goals against and the other team have 2 and 1 goals against respectively it will output both teams instead of just the lowest.

Sorry it's difficult to explain. Hopefully someone can give some assistance

Thanks

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
  void DoBestDefence(void)

	{
		int lowestgoalsagainst = 0;
		for (int i = 0; i < numTeamsInLeague; i++)
		{

			if (league[i].GetGoalsAgainst() >= lowestgoalsagainst)

			{
				lowestgoalsagainst = league[i].GetGoalsAgainst();
			}


		}

		for (int i = 0; i < numTeamsInLeague; i++)
		{
			if (league[i].GetGoalsAgainst() < lowestgoalsagainst)
			{
				cout << league[i].GetName() << " " << league[i].GetGoalsAgainst();
				
			}
		}

	}
You should just keep track of the lowest and then ouput that team's index?
1
2
3
4
5
6
7
8
9
10
int lowestGoalsAgainstIndex = 0, lowestGoalsAgainst = league[0].GetGoalsAgainst(); // set lowest to first team
for (int i = 0; i < numTeamsInLeague; i++)
{
  if (league[i].GetGoalsAgainst() < lowestgoalsagainst) // check lowest against current indexed team
  {
    lowestGoalsAgainst = league[i].GetGoalsAgainst(); // update lowest goals
    lowestGoalsAgainstIndex = i; // store index for "lowest" team
  }
}
cout << league[lowestGoalsAgainstIndex].GetName() << " " << lowestGoalsAgainst; // output team name and goals against stat 


EDIT: If there are multiple teams tied for lowest, obviously this method wouldn't do
Last edited on
Why do you use >= on line 8 instead of < for comparison? It looks like you need some sleep.
Last edited on
I just got it to work out after posting

Yours seems like a better solution. But I'll show what I had anyway

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
void DoBestDefence(void)

	{
		int lowestgoalsagainst = 0;
		for (int i = 0; i < numTeamsInLeague; i++)
		{

			if (league[i].GetGoalsAgainst() >= lowestgoalsagainst)

			{
				lowestgoalsagainst = league[i].GetGoalsAgainst();
			}


		}

		string bestdefense = " ";
		for (int i = 0; i < numTeamsInLeague; i++)
		{
			if (league[i].GetGoalsAgainst() < lowestgoalsagainst)
			{
				
				lowestgoalsagainst = league[i].GetGoalsAgainst();
				bestdefense = league[i].GetName();
				
			}
		}

		cout << bestdefense << " " << lowestgoalsagainst;
	}


Thanks for Help
Topic archived. No new replies allowed.