我在C#中使用Arrays编写了这个程序。这是家庭作业。我几乎已经在程序中写了所有内容,但我仍然坚持清除阵列。我以为我有它,但我不明白它在哪里工作。
该计划非常简单。用户输入分数并点击“添加”按钮。然后用户可以输入更多分数(任何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);
}
}
}
答案 0 :(得分:1)
您需要在清除数组的同时将变量Total
置零。