From 778fec0b34d4982c259daeb0ba8d52b830f8e071 Mon Sep 17 00:00:00 2001 From: "Federico Pasqua (eisterman)" Date: Sun, 2 Nov 2025 14:52:19 +0100 Subject: [PATCH] Ch2Weather: add TemperatureStatsDisplay --- Ch2Weather/Program.cs | 1 + Ch2Weather/Weather.cs | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/Ch2Weather/Program.cs b/Ch2Weather/Program.cs index c922dd9..76d01d8 100644 --- a/Ch2Weather/Program.cs +++ b/Ch2Weather/Program.cs @@ -5,6 +5,7 @@ using Ch2Weather; var weatherData = new WeatherData(new WeatherRecord(0, 0,0)); _ = new CurrentConditionsDisplay(weatherData); _ = new HeatIndexDisplay(weatherData); +_ = new TemperatureStatsDisplay(weatherData); weatherData.WeatherRecord = new WeatherRecord(25, 50, 30); weatherData.WeatherRecord = new WeatherRecord(35, 55, 29.8); weatherData.WeatherRecord = new WeatherRecord(45, 60, 29.6); \ No newline at end of file diff --git a/Ch2Weather/Weather.cs b/Ch2Weather/Weather.cs index cd13504..0002022 100644 --- a/Ch2Weather/Weather.cs +++ b/Ch2Weather/Weather.cs @@ -92,4 +92,37 @@ public class HeatIndexDisplay : IWeatherObserver, IWeatherDisplay { var heatIndex = ComputeHeatIndex(_weatherRecord.Temperature, _weatherRecord.Humidity); 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}"); + } } \ No newline at end of file