Ch2Weather: add TemperatureStatsDisplay

This commit is contained in:
2025-11-02 14:52:19 +01:00
parent 3c2948a5d1
commit 778fec0b34
2 changed files with 34 additions and 0 deletions

View File

@@ -5,6 +5,7 @@ using Ch2Weather;
var weatherData = new WeatherData(new WeatherRecord(0, 0,0)); var weatherData = new WeatherData(new WeatherRecord(0, 0,0));
_ = new CurrentConditionsDisplay(weatherData); _ = new CurrentConditionsDisplay(weatherData);
_ = new HeatIndexDisplay(weatherData); _ = new HeatIndexDisplay(weatherData);
_ = new TemperatureStatsDisplay(weatherData);
weatherData.WeatherRecord = new WeatherRecord(25, 50, 30); weatherData.WeatherRecord = new WeatherRecord(25, 50, 30);
weatherData.WeatherRecord = new WeatherRecord(35, 55, 29.8); weatherData.WeatherRecord = new WeatherRecord(35, 55, 29.8);
weatherData.WeatherRecord = new WeatherRecord(45, 60, 29.6); weatherData.WeatherRecord = new WeatherRecord(45, 60, 29.6);

View File

@@ -92,4 +92,37 @@ public class HeatIndexDisplay : IWeatherObserver, IWeatherDisplay {
var heatIndex = ComputeHeatIndex(_weatherRecord.Temperature, _weatherRecord.Humidity); var heatIndex = ComputeHeatIndex(_weatherRecord.Temperature, _weatherRecord.Humidity);
Console.WriteLine($"Heat Index is {heatIndex}"); Console.WriteLine($"Heat Index is {heatIndex}");
} }
}
public class TemperatureStatsDisplay : IWeatherObserver, IWeatherDisplay {
private IWeatherSubject _subject;
private double _n = 0;
private double _avg = 0;
private double _min = 0;
private double _max = 0;
public TemperatureStatsDisplay(IWeatherSubject subject) {
_subject = subject;
subject.Subscribe(this);
}
public void Update(WeatherRecord wr) {
var temp = wr.Temperature;
if (_n == 0) {
_n = 1;
_avg = temp;
_min = temp;
_max = temp;
} else {
_min = double.Min(_min, temp);
_max = double.Max(_max, temp);
_avg = (_avg * _n + temp) / (_n + 1);
_n += 1;
}
Display();
}
public void Display() {
Console.WriteLine($"Avg/Max/Min Temperature: {_avg}/{_max}/{_min}");
}
} }