Reputation:
i'm attempting to learn C# and I have this code. I want it to display a random list of integers and then add them all together within the array and then display the average of all the numbers. Where have I gone wrong, can anyone help? Thanks.
using System;
class grades
{
public static void Main(string[] args)
{
int sumValue = 0;
int[] grades = new int [ 30 ];
Random rnd = new Random();
for (int i = 0; i < 30; i++)
grades[i] = rnd.Next(1,101);
foreach (int i in grades)
{
Console.WriteLine("{0}", i);
sumValue = sumValue + i;
}
double average = sumValue/30;
Console.WriteLine("{0}", average);
}
}
Upvotes: 2
Views: 108
Reputation: 1062770
Yeah, the random integers are displayed but the adding and the average isn't calculated.
Yes, it is; you can make it more obvious:
double average = sumValue / 30.0;
Console.WriteLine("The average is: {0:##0.0}", average);
Note also the .0
which ensures we aren't doing integer arithmetic (different fraction / rounding rules).
Upvotes: 5