0

我使用 C# 中的数组编写了这个程序。这是家庭作业。我几乎已经在程序中编写了所有内容,但我一直在清除数组。我以为我有它,但我不明白它在哪里不起作用。

该程序非常简单。用户输入分数并点击“添加”按钮。然后用户可以输入更多分数(0 到 100 之间的任何值)。如果用户选择“显示”,程序将对输入的分数进行排序,并在用户按下“清除分数”按钮时将它们显示在消息框(完成)中,程序应该清除分数。我写了它来清除文本框,我还在那里写了“Scores.Clear();” (分数是我的列表数组的名称),然后我将焦点返回到我的分数输入文本框,以便用户可以输入另一个分数。

我正在使用的书只是说清除类型 NameOfList.Clear(); 所以我坚持为什么它没有清​​除。我可以说这不是因为如果我输入更多分数,它将添加总数而不是重新开始。

这是我的完整程序代码。我的清除开始大约一半。

先感谢您。

{
public partial class frmScoreCalculator : Form
{
    //declare a list array for scores
    List<int> Scores = new List<int>();

    //set total and average to 0 
    int Total = 0;
    decimal Average = 0;


    public frmScoreCalculator()
    {
        InitializeComponent();
    }

    //calculate the average by dividing the sum by the number of entries
    private decimal CalculateAverage(int sum, int n)
    {
        Average = sum / n;

        return Average;
    }
    private void frmScoreCalculator_Load(object sender, EventArgs e)
    {

    }

    //closes the program. Escape key will also close the program
    private void btnExit_Click(object sender, EventArgs e)
    {
        this.Close();
    }


    //clears the text boxes, clears the array, returns focus back to the score text box like a boss.
    private void btnClear_Click(object sender, EventArgs e)
    {
        txtScore.Text = "";
        txtCount.Text = "";
        txtTotal.Text = "";
        txtAverage.Text = "";
        Scores.Clear();
        txtScore.Focus();
    }

    //makes sure the score is within the valid range, calculates the average, adds to the number of
    //scores entered, and adds to the total
    private void btnAdd_Click(object sender, EventArgs e)
    {
        if (txtScore.Text == string.Empty)
        {
            txtScore.Focus();
            return;
        }


        int Score = int.Parse(txtScore.Text);

        if (Score > 0 && Score < 100)
        {
            Scores.Add(Score);

            Total += Score;
            txtTotal.Text = Total.ToString();

            txtCount.Text = Scores.Count.ToString();

            Average = CalculateAverage(Total, Scores.Count);
            txtAverage.Text = Average.ToString();

            txtScore.Text = string.Empty;
            txtScore.Focus();

        }

        // if number is not valid, ask user for valid number
        else
        {
            MessageBox.Show("Please enter a number between 0 and 100.", "ENTRY ERROR, DO IT RIGHT!");

        }

        // returns focus to txtNumber
        txtScore.Focus();
        txtScore.Text = "";
    }

    //display button
    private void btnDisplay_Click(object sender, EventArgs e)
    {
        //sorts the scores low to high
        Scores.Sort();

        //displays scores in message box
        string DisplayString = "Sorted Scores :\n\n";

        foreach (int i in Scores)
        {
            DisplayString += i.ToString() + "\n";
        }

        MessageBox.Show(DisplayString);
    }
}

}

4

1 回答 1

1

您需要Total在清除数组的同时将变量归零。

于 2013-10-13T16:11:45.183 回答