如何显示和计算平均值?如何只将值写入文本文件一次?

时间:2014-01-01 14:51:04

标签: c# winforms

这是代码:

double value = Convert.ToDouble(sensor.Value);
if (value < minTemp) minTemp = value;
if (value > maxTemp) maxTemp = value;

label8.Text = maxTemp.ToString() + "c";
label8.Visible = true;
label9.Text = minTemp.ToString() + "c";
label9.Visible = true;
temperature_label.Text = sensor.Value.ToString() + "c";
int t = temperature_label.Text.Length;
if (t > 3)
{
   temperature_label.Location = new Point(238, 200);
}

label8显示最高温度标签9显示最小值和temeprature_label显示当前值。 我想添加一个标签,实时显示当前的平均值。我该怎么办?

在代码的这一部分中,我将当前的temeprature写入记录器(文本)文件,如果它高于用户设置的温度:

if (sensor.Value > float.Parse(textbox3_value))
{
     Logger.Write("The current temperature is ===> " + sensor.Value);
     button1.Enabled = true;
}

问题是所有这些代码都在一个每秒更新的计时器滴答中。 它写入Logger文件,每次添加新行时都会添加。

例如,记录器文件如下所示:

1/1/2014--12:50 PM ==> The current temperature is ===> 71
1/1/2014--12:50 PM ==> The current temperature is ===> 71
1/1/2014--12:50 PM ==> The current temperature is ===> 71
1/1/2014--12:50 PM ==> The current temperature is ===> 71
1/1/2014--12:50 PM ==> The current temperature is ===> 71
1/1/2014--12:50 PM ==> The current temperature is ===> 72
1/1/2014--12:50 PM ==> The current temperature is ===> 72
1/1/2014--12:50 PM ==> The current temperature is ===> 73
1/1/2014--12:50 PM ==> The current temperature is ===> 74
1/1/2014--12:50 PM ==> The current temperature is ===> 73
1/1/2014--12:50 PM ==> The current temperature is ===> 73

我想让记录器文件格式如下:

1/1/2014--12:50 PM ==> Session Started
1/1/2014--12:50 PM ==> The current temperature is ===> 71
1/1/2014--12:50 PM ==> The last highest temperature was ===> 80
1/1/2014--12:50 PM ==> The last minimum temperature was ===> 40
1/1/2014--12:50 PM ==> The average temperature is ===> 75

如果其中一行有新值,它将更新此行值,并且不会添加新行。

这是Logger类中的Write方法:

public static void Write(string str)
{
    if (mut.WaitOne() == false)
    {
        return;
    }
    else
    {
        using (StreamWriter sw = new StreamWriter(full_path_log_file_name, true))
        {
            sw.Write(DateTime.Now.ToShortDateString() + "--" + DateTime.Now.ToShortTimeString() + " ==> " + str);
            sw.WriteLine();
            sw.Close();
        }
    }
    mut.ReleaseMutex();
} 

1 个答案:

答案 0 :(得分:1)

首先定义一个列表来存储所有值,并定义一个变量来存储平均值:

List<int> values = new List<int>();
double average = 0.0;

在这里:

double value = Convert.ToDouble(sensor.Value);
values.Add(value);
average = values.Average();
Logger.Write("The average temperature is ===> " + average);