0

Having trouble with Math.Min within a method. keeps initialising back to 0

//Current method public GradeStatistics ComputeStatistics() { GradeStatistics stats = new GradeStatistics(); float sum = 0; foreach (float grade in grades) { stats.HighestGrade = Math.Max(grade, stats.HighestGrade); stats.LowestGrade = Math.Min(grade, stats.LowestGrade); sum += grade; } stats.AverageGrade = sum / grades.Count; return stats; } // Current Main static void Main(string[] args) { GradeBook book = new GradeBook(); book.AddGrade(91); book.AddGrade(56.5f); book.AddGrade(75); GradeStatistics stats = book.ComputeStatistics(); Console.WriteLine(stats.AverageGrade); Console.WriteLine(stats.HighestGrade); Console.WriteLine(stats.LowestGrade); } Has no issues running the average or highest. but for some reason stats.LowestGrade keeps giving me the default value, instead of 56.6f any help would be much appreciated

24th Feb 2018, 9:12 PM
Chris
6 Réponses
24th Feb 2018, 11:47 PM
John Wells
John Wells - avatar
+ 1
If your default value is 0, it will stay the minimum. Default to 100.
24th Feb 2018, 9:49 PM
John Wells
John Wells - avatar
+ 1
Link your code so we can run it. Using the app there is a + Insert... button OR share your code and copy to clipboard followed by pasting in the post.
24th Feb 2018, 10:22 PM
John Wells
John Wells - avatar
0
make your stat.LowestGrade as the maximum grade possible before the first iteration, that might help
24th Feb 2018, 10:11 PM
Amaras A
Amaras A - avatar
0
odd, for some reason it's still resulting in 0 and now my average is thrown off.
24th Feb 2018, 10:15 PM
Chris
0
class Program { static void Main(string[] args) { GradeBook book = new GradeBook(); book.AddGrade(91); book.AddGrade(56.5f); book.AddGrade(75); GradeStatistics stats = book.ComputeStatistics(); Console.WriteLine(stats.AverageGrade); Console.WriteLine(stats.HighestGrade); Console.WriteLine(stats.LowestGrade); } } /*************************************************/ public class GradeBook { public GradeBook() { grades = new List<float>(); } public GradeStatistics ComputeStatistics() { GradeStatistics stats = new GradeStatistics(); float sum = 0; foreach (float grade in grades) { stats.HighestGrade = Math.Max(grade, stats.HighestGrade); stats.LowestGrade = Math.Min(grade, stats.LowestGrade); sum += grade; } stats.AverageGrade = sum / grades.Count; return stats; } public void AddGrade(float grade) { grades.Add(grade); } public string Name; private List<float> grades; } } /**********************************************/ public class GradeStatistics { public float AverageGrade; public float HighestGrade; public float LowestGrade; } /* those are the three classes i have. Thank you all so much for the help! */
24th Feb 2018, 10:52 PM
Chris