Forums: » Register « |  Free Tools |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support |

New Free Tools on Dev Shed!

#1
May 8th, 2011, 10:49 AM
 willy155
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();
{
}

{
int d = Convert.ToInt32(c);

}
double average = Math.Round(avg);
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

avg = 51
average = 51

can someone work out why my code is not doing what it should?

#2
May 8th, 2011, 01:54 PM
 David_B
Contributing User

Join Date: Mar 2006
Posts: 68
Time spent in forums: 1 Day 1 h 37 m 58 sec
Reputation Power: 23
The character "1" has an ASCII value of 49, so it looks like it is not being converted into an integer. The variable d is simply getting the ASCII equivalents of all the characters in the input string. Check that conversion function.
__________________
Regards,

David
Quadratic Equation Solver . . . and more.

#3
May 8th, 2011, 09:25 PM
 willy155
Contributing User

Join Date: Feb 2010
Posts: 51
Time spent in forums: 13 h 24 m 24 sec
Reputation Power: 4
sorted now...you were right, it was to do with the conversion. all i had to change the offending line to was:

Code:
`int d = Convert.ToInt32(c.ToString());`

 Viewing: Dev Shed Forums > Programming Languages > C Programming > Reading string of numbers from .txt file and calculating two values from the numbers