这有帮助吗?(老实说,你的问题是模糊和开放式的......)
以下代码在单击某个按钮时向页面显示一些信息。它显示了人口的平均变化,人口增长最多和最少的年份。
private void btnFindPopulation_Click(object sender, EventArgs e)
{
StreamReader inputFile = File.OpenText("USPopulation.txt"); //Open the USPopulation.txt file.
List<int> PopulationList = new List<int>(); //Creates a list and a new object of the list.
int startingyear = 1950; //Creates the starting year for the index.
while (!inputFile.EndOfStream) //While not at the end of the list.
{
PopulationList.Add(int.Parse(inputFile.ReadLine())); //Read the scores into the list.
}
inputFile.Close(); //Close the file.
int numberOfYears = PopulationList.Count(); //Counts the amount of items in the population and assigns it to number of years.
int average = Average(PopulationList, numberOfYears); //Sends the population list and numberofyears into average.
lblAnnualChange.Text = average.ToString(); //Assigns the new average into the lblAnnualChange.
int biggest = startingyear + GreatestIncrease(PopulationList); //Adds the starting year with the index count of the biggest number.
lblGreatestIncrease.Text = biggest.ToString(); //Assigns the biggest into the lblGreatestIncrease.
int least = startingyear + LeastIncrease(PopulationList); //Sends the population list and number of years to least number.
lblLeastIncrease.Text = least.ToString(); //Assigns the least into the lblLeastIncrease.
}
调用其他方法来整理数据:Average 是超前的。但是 GreatestIncrease 和 LeastIncrease 正在搜索数据列表(假设它已经从最早到最新排序,这是一个糟糕的假设,如果你问我......)以确定哪一年(或实际上是列表索引)包含最大的变化(或最小的变化,在 LeastIncrease 的情况下)。
方法名称给出的不好,并且不能很好地传达它返回的数据。如果我正在查看此代码,我建议将方法名称分别更改为“GetIndexOfGreatestIncrease”和“GetIndexOfLeastIncrease”。
private int GreatestIncrease(List<int> PopulationList) //Imports the population list to Greatest.
{
int amountOfChange = 0;
int changeInYears = 0;
int i;
int theChange = 0;
int currentYear = 0;
for (i = 1; i < PopulationList.Count(); i++)
{
theChange = PopulationList[i] - PopulationList[i - 1];
currentYear = i;
if (theChange > amountOfChange)
{
amountOfChange = theChange;
changeInYears = i;
}
}
return changeInYears;
}
private int LeastIncrease(List<int> PopulationList) //Imports the population list to Least.
{
int firstItem = PopulationList.First();
int lastItem = PopulationList.Last();
int amountOfChange = (lastItem - firstItem);
int changeInYears = 0;
int i;
int theChange = 0;
int CurrentYear = 0;
for (i = 1; i < PopulationList.Count(); i++)
{
theChange = PopulationList[i] - PopulationList[i - 1];
CurrentYear = i;
if (theChange < amountOfChange)
{
amountOfChange = theChange;
changeInYears = i;
}
}
return changeInYears;
}
另外,欢迎来到 Stack Overflow!请对不能完全回答您问题的答案发表评论,并将最适合的答案标记为答案。通常,您对答案的评论也会导致改进您提出的问题的方法。