2

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); 
    }
}
2
  • Well, what exactly behaves unexpectedly? can you be explicit? Commented Nov 25, 2014 at 12:02
  • Yeah, the random integers are displayed but the adding and the average isn't calculated. Commented Nov 25, 2014 at 12:04

1 Answer 1

5

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).

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. Just me being stupid and forgetting to make it stand out. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.