我正在尝试创建一个基本的天气应用程序,您可以在其中输入城市的读数,它将显示平均温度,最低温度和最高温度。
我创建了一个包含5行(城市)和4列(4个读数)的2d数组(intTemps)。每当我向列表框添加温度时,它总是显示在左上角。当我添加另一个温度时,它会显示刚刚显示的温度和当前温度。
代码是基于我教授写的一个例子,所以我不确定为什么它显示不正确。
public partial class Form1 : Form
{
string[] strNames = { "Livonia",
"Redford" ,
"Novi" ,
"Westland",
"Northville" };
int[,] intTemps = new int[5, 4];
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
for (int i = 0; i <= 4; i++)
{
cobNames.Items.Add(strNames[i]);
lstNames.Items.Add(strNames[i]);
}
}
private void btnAdd_Click(object sender, EventArgs e)
{
try
{
if (cobNames.SelectedIndex >= 0 && cobNames.SelectedIndex <= 4)
{
if (intTemps[cobNames.SelectedIndex, (int)nudTemp.Value - 1] == 0)
{
intTemps[cobNames.SelectedIndex, (int)nudTemp.Value - 1] = Int32.Parse(txtTemp.Text);
}
else
{
MessageBoxButtons buttons = MessageBoxButtons.YesNo;
DialogResult result;
result = MessageBox.Show("Do you want to change temps?", "Temps already exist!", buttons);
if (result == System.Windows.Forms.DialogResult.Yes)
{
intTemps[cobNames.SelectedIndex, (int)nudTemp.Value - 1] = Int32.Parse(txtTemp.Text);
}
}
displayTemps();
}
else
{
MessageBox.Show("You must select a valid name!");
}
}
catch (FormatException)
{
MessageBox.Show("Temps must be integers");
}
}
private void displayTemps()
{
string strLine;
lstTemp.Items.Clear();
double[] dblAverages = new double[5];
int intNonBlank = 0;
for (int l = 0; l <= 4; l++)
{
intNonBlank = 0;
for (int c = 0; c <= 3; c++)
{
if (intTemps[l, c] != 0)
{
dblAverages[l] += intTemps[l, c];
intNonBlank++;
}
}
if (intNonBlank != 0)
{
dblAverages[l] /= intNonBlank;
}
}
for (int l = 0; l <= 4; l++)
{
strLine = " ";
for (int c = 0; c <= 3; c++)
{
if (intTemps[l, c] == 0)
{
strLine += " ";
}
else
{
if (intTemps[l, c] == 120)
{
strLine += intTemps[l, c] + " ";
}
else
{
strLine += intTemps[l, c] + " ";
}
lstTemp.Items.Add(strLine);
}
}
}
}
}
答案 0 :(得分:0)
我重写你的显示Temps()程序。这将向lstTemp
添加您需要的所有信息:
private void displayTemps()
{
string strLine;
lstTemp.Items.Clear();
double[] dblAverages = new double[5];
int intNonBlank = 0;
for (int l = 0; l <= 4; l++)
{
intNonBlank = 0;
for (int c = 0; c <= 3; c++)
{
if (intTemps[l, c] != 0)
{
dblAverages[l] += intTemps[l, c];
intNonBlank++;
}
}
if (intNonBlank != 0)
{
dblAverages[l] /= intNonBlank;
}
int min_temp = System.Linq.Enumerable.Range(0, 4).
Select(i => intTemps[l, i]).Min();
int max_temp = System.Linq.Enumerable.Range(0, 4).
Select(i => intTemps[l, i]).Max();
lstTemp.Items.Add(
"Average temp for city "+ l +": " + dblAverages[l] + " " +
"Minimum " + min_temp + " " +
"Maximum " + max_temp);
}
}