Davey
Davey

Reputation: 129

Computing a Win/Loss Percentage

I need to compute the percentage of games won and games lost. I keep getting errors and it's driving me up a wall. I've changed my code so many times that I don't really remember what it was like when I started.

Private Sub btnPercentage_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPercentage.Click
    Dim team As String
    Dim won, lost, percentage As Integer

    team = CStr(txtTeam.Text)
    won = CInt(txtGamesWon.Text)
    lost = CInt(txtGamesLost.Text)
    percentage = CInt(txtPercent.Text)

    percentage = (won + lost) / 2

    txtPercent.Text = team & " won" & percentage & " of its games."

Upvotes: 0

Views: 5490

Answers (6)

RKitson
RKitson

Reputation: 2013

Most of your problem here isn't even programming related.

It would help to know the simple math behind calculating a percentage first. This one should have been relatively simple to work out on paper first.

My eyes started bleeding when I read:

percentage = (won + lost) / 2.

Percentage should not be equal to half the number of games played (although many a MLB team would dig having that record).

Upvotes: 0

ggf31416
ggf31416

Reputation: 3647

Dim team as String = txtTeam.Text  
Dim won as Integer = Cint(txtGamesWon.Text)  
Dim lost as Integer = CInt(txtGamesLost.Text)  
Dim percentage as Integer = Cint(won / (won + lost) * 100)  
txtPercent.Text = team & " won " & percentage & "% of its games."  

If you want to make it more resistent to bad inputs you could use Integer.TryParse rather than Cint.

Upvotes: 2

Yes - that Jake.
Yes - that Jake.

Reputation: 17121

percentage = won / (won + lost)

BTW, if Visual Studio doesn't barf on:

Dim won, lost, percentage As Integer

It will dim won and lost as objects, not integers.

Upvotes: 0

Chad Birch
Chad Birch

Reputation: 74528

Think the problem through in your head first before you start writing the code. Right now this is the way your code is working:

"Team A has won 5 games and lost 3, so the percentage of games it has won is (5 + 3) / 2 = 4%"

Probably the single most important skill as a programmer is the ability to break problems down into steps for the computer to perform, make sure you've figured out the right steps before you start writing them.

Upvotes: 6

S.Lott
S.Lott

Reputation: 391846

percentage = (won + lost) / 2 can't be right.

Isn't the percentage won percentage_won = won / (won + lost).

And the percentage lost percentage_lost = lost / (won + lost).

Upvotes: 1

BoltBait
BoltBait

Reputation: 11489

Percentage won = total won / (total won + total lost)

You may have to multiply that by 100 for display purposes.

Upvotes: 2

Related Questions