在TextBox中显示数学运算

时间:2018-04-20 14:19:30

标签: c# asp.net

我是ASP的初学者,我有这个代码。它假设在按钮"计算"之后,在单独的文本框中显示数组中三个数字的和,产品和平均值。被压了。但是,每当我在文本框中放入三个值并按下计算时,它只显示零!

protected void MathOps(object sender, EventArgs e)
{
    double[] arr = new double[3];

    double sum = 0;
    double product = 0;
    double average = 0;

    for (int i = 0; i < arr.Length; i++)
    {
        sum += arr[i];
        product *= arr[i];
        average = sum / arr.Length;

        TextBox6.Text = sum.ToString();
        TextBox7.Text = product.ToString();
        TextBox8.Text = average.ToString();
    }
}
表格的

This is a picture以获得更多说明

2 个答案:

答案 0 :(得分:1)

它应该是这样的(简化代码):

protected void MathOps(object sender, EventArgs e)
{
    //TODO: Simplification: we assume all TextBox1.Text..TextBox3.Text have valid values
    double[] arr = new double[] {
      double.Parse(TextBox1.Text), 
      double.Parse(TextBox2.Text),
      double.Parse(TextBox3.Text),  
    };

    double sum = 0;
    double product = 1;
    double average = 0;

    for (int i = 0; i < arr.Length; i++)
    {
        sum += arr[i];
        product *= arr[i];
    }

    average = sum / arr.Length;

    //DONE: There's no need to output in each iteration
    TextBox6.Text = sum.ToString();
    TextBox7.Text = product.ToString();
    TextBox8.Text = average.ToString();
}

答案 1 :(得分:0)

您没有初始化arr。

double [] arr = new double [3]

上面一行创建一个3个双精度数组,默认值为0.0。 所以首先初始化它

protected void MathOps(object sender, EventArgs e)
{

    double[] arr = new double[3];
    arr[0]  = 3.0, arr[1] =4.0 , arr[2]=5.0


double sum = 0;
double product = 0;
double average = 0;

for (int i = 0; i < arr.Length; i++)
{
    sum += arr[i];
    product *= arr[i];
    average = sum / arr.Length;

    TextBox6.Text = sum.ToString();
    TextBox7.Text = product.ToString();
    TextBox8.Text = average.ToString();
}

}

此代码可以使用。