为什么我的“计算”不起作用?

时间:2011-09-24 04:27:14

标签: c#

我需要创建一个简单的c#应用程序来添加一些季度数字。我使用数组“存储”数据,然后将其放在文本框中。

无论如何,我的计算部分存在一些问题。我已在其周围添加了评论标签,以便您可以轻松找到它。该区域有效,但需要两次点击并将其添加到上面的行。我一直看着相同的几行大约一个小时,似乎无法想象这一行。有什么想法吗?

    //Global
    int lastIndexUsed = -1;
    int[,] quarters = new int[10, 5];
    string[] Branch = new string[10];

    public FrmSales()
    {
        InitializeComponent();
    }

    private void txtBranch_TextChanged(object sender, EventArgs e)
    {

    }

    private void btnCalc_Click(object sender, EventArgs e)
    {
        int Q1;
        int Q2;
        int Q3;
        int Q4;


        Q1 = int.Parse(txtQ1.Text);
        Q2 = int.Parse(txtQ2.Text);
        Q3 = int.Parse(txtQ3.Text);
        Q4 = int.Parse(txtQ4.Text);

        lastIndexUsed = lastIndexUsed + 1;
        quarters[lastIndexUsed, 0] = Q1;
        quarters[lastIndexUsed, 1] = Q2;
        quarters[lastIndexUsed, 2] = Q3;
        quarters[lastIndexUsed, 3] = Q4;
        Branch[lastIndexUsed] = txtBranch.Text;








        //Display Results

        int ctr;
        int ctr2;
        string outLine;
        string tempName;

        int row;
        int col;
        int accum;


        txtInfo.Text = "";

        outLine =           "  Branch       Q1         Q2         Q3         Q4       Total   " + "\r\n";
        outLine = outLine + "========== ========== ========== ========== ========== ==========" + "\r\n";

        txtInfo.Text = outLine;


        for (ctr = 0; ctr <= lastIndexUsed; ctr++)
        {

            outLine = "";

            tempName = Branch[ctr].PadLeft(10);
            outLine = outLine + tempName + " ";

            for (ctr2 = 0; ctr2 <= 4; ctr2 = ctr2 + 1)

            {


                outLine = outLine + quarters[ctr, ctr2].ToString().PadLeft(10) + " ";

            }

            txtInfo.Text = txtInfo.Text + outLine + "\r\n";


        }

        //Calculate ###########################################################

        for (row = 0; row <= lastIndexUsed; row++)
        {

            accum = 0;


            for (col = 0; col <= 3; col++ )
            {

                accum = accum + quarters[row, col];

            }
            quarters[row, 4] = accum;
        }




        //End Calculate #########################################################

    }

    private void btnClear_Click(object sender, EventArgs e)
    {
        txtBranch.Text = "";
        txtQ1.Text = "";
        txtQ2.Text = "";
        txtQ3.Text = "";
        txtQ4.Text = "";
        txtInfo.Text = "";

    }

    private void btnExit_Click(object sender, EventArgs e)
    {
        Close();
    }

1 个答案:

答案 0 :(得分:5)

问题很简单:在实际计算值之前使用quarters数组。将“calculate”循环移动到第一个循环之上。

另外(除其他外):

  • 太多空行和空格;使其难以阅读
  • 不要尝试使用文本制作格式化报告;只需使用DataGridView或类似的
  • 如果单击按钮足够多次,则会有一个数组索引超出范围的异常,因为lastIndexUsed将超过10。