Ryan Dougan Ryan Dougan - 22 days ago 6
ASP.NET (C#) Question

Finding the mean of numbers in a text box

Okay so I want to calculate the mean of an array based on users input. I have a textbox where users will enter numbers and the numbers will be split by a comma. So the text box will look like 23, 11, 24, 45 etc. As you see below I currently have it pulling from hard coded array for now.

Front End Code

<p>Please enter your numbers within the textbox provided</p>

<asp:TextBox ID="userInput" runat="server"></asp:TextBox>
<br />
<div>
<p>The mean is:</p>

<asp:TextBox ID="meanTextBox" runat="server"></asp:TextBox>
<asp:Button ID="calculateResults" runat="server" Text="Button" OnClick="calculateResults_Click" />


Back End Code of Button

protected void calculateResults_Click(object sender, EventArgs e)
{
int[] numbers = { 4, 4, 4, 4, 3, 2, 2, 2, 1 };

double mean = numbers.Average();

meanTextBox.Text = mean.ToString();
}

Answer

You need to convert the string input from the checkbox to the string[]. This can be done with splitting by ' '. After that you need to convert the string[] to int[] and in last step is to calculate the mean value which is Average/NumberOfElements.

    decimal valueOf = 0;

    var myInts = Array.ConvertAll(userInput.Text.Split(' '), s => decimal.TryParse(s, out valueOf) ? valueOf: 0);

    var mean= myInts.Average() / myInts.Count();
    meanTextBox.Text = mean.ToString();

Here we go.