1

Need to find a fix to this implicit cast error to get the code to compile. The code is:

// Program calls a method that finds and returns
// the median value in an array
// The median value is the middle value from largest to smallest
// If there are an even number of values, the
// median is the mean of the two middle values
using System;
using static System.Console;
class DebugSeven4
{
    static void Main()
    {
        double[] firstArray = { 10, 9, 2, 3, 5, 6 };
        double[] secondArray = { 112, 456, 782 };
        double[] thirdArray = { 9, 12, 45, 82, 84, 67, 2, 6 };
        WriteLine("The median value of the first array is {0}",
           FindMedian(firstArray));
        WriteLine("The median value of the second array is {0}",
           FindMedian(secondArray));
        WriteLine("The median value of the third array is {0}",
           FindMedian(thirdArray));
    }
    private static double FindMedian(double[] array)
    {
        double median;
        double middle = array.Length / 2;
        Array.Sort(array);
        if (array.Length % 2 == 0)
            median = (double)(array[middle - 1] + array[middle]) / 2;
        else
            median = (double) array[middle];
        return median;
    }
}

The error is "Cannot implicit convert type double to int. Could be missing a cast." but I'm not certain that's the actual problem. It appears to be complaining about the middle variable.

paxdiablo
  • 814,905
  • 225
  • 1,535
  • 1,899
Vector 2755
  • 37
  • 1
  • 5
  • Not sure *any* of the proposed duplicates are actually duplicates. Despite the question, this really has nothing to do with converting to an integer, the variable (an array index) should never have been floating point in the first place. – paxdiablo Oct 22 '19 at 00:01
  • 1
    @Keith, despite the title of this question, it has *nothing* to do with converting a double to an int. The variable, which is an array index, should never have been a double in the first place. I'd had this discussion previously with mjwills. Will try to edit to make that clearer. – paxdiablo Oct 22 '19 at 03:40
  • 1
    @paxdiablo reopened – Keith Nicholas Oct 22 '19 at 04:08

1 Answers1

3

Re:

double middle = array.Length / 2;

Since array indexes are integers anyway, that should probably just be an integer:

int middle = array.Length / 2;

Then the casting problem just goes away.

paxdiablo
  • 814,905
  • 225
  • 1,535
  • 1,899