Ch2Weather: add TemperatureStatsDisplay
This commit is contained in:
@@ -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}");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user