
May 8th, 2011, 09:49 AM
|
|
Contributing User
|
|
Join Date: Feb 2010
Posts: 51
Time spent in forums: 13 h 24 m 24 sec
Reputation Power: 4
|
|
|
Reading string of numbers from .txt file and calculating two values from the numbers
I am having troubles sorting out what should be a very simple piece of code. It takes in a string of numbers (which represent votes out of 5 for something) from a .txt file and should then work out the total number of votes, and the average of those votes. It is getting the total number of votes right but for some reason it is messing up on the average...the code is as follows:
Code:
public Form1()
{
InitializeComponent();
string votes = System.IO.File.ReadAllText(@"..\..\votes.txt");
int votesSum = 0;
int totalVotes = 0;
foreach (char b in votes)
{
totalVotes++;
}
foreach (char c in votes)
{
int d = Convert.ToInt32(c);
votesSum = votesSum + d;
}
Console.Write(votesSum);
double avg = votesSum / totalVotes;
double average = Math.Round(avg);
lblTotal.Text = totalVotes.ToString();
lblAvg.Text = average.ToString();
}
the current contents of 'votes.txt' are:
134253413243524
I make the total votes to be 15, the sum should be 46 and the average should be 3.06(recurring)
I've tried inserting a breakpoint in at the start of the second foreach loop but for some reason (on the first iteration) its saying the following:
d = 49
c = 49 '1'
when i step through the whole code it says
votesSum = 766
totalVotes = 15
avg = 51
average = 51
can someone work out why my code is not doing what it should?
|