Domanda

Im finding the middle position of an array, but if it is an even set of arrays i must find the average of the two middle numbers. i have the variable initialized as a double; but it still wont work. I've tried setprecision and the correct values are being found.

void median (int *pScores, int numScores)
{
    insertionSort(pScores, numScores);

    int mid = 0;
    int midRight = 0;
    int midLeft = 0;
    double midEven;

    //if array is odd
    if (numScores % 2 != 0)
    {
        mid = numScores / 2;
        cout << "Middle Position: " << *(pScores + mid) << endl;
    }

    //if array is even
    if (numScores % 2 == 0)
    {
        midRight = (numScores/2);
        midLeft = (numScores/2) - 1;


        cout << *(pScores + midRight) << endl;
        cout << *(pScores + midLeft) << endl;

        midEven = ( *(pScores + midRight) + *(pScores + midLeft) ) / 2;
        cout << "Median: "<< setprecision(2) << midEven << endl;
    } 
}

I've tried initializing double midEven as double midEven = 0; and double midEven = 0.0; and I'm still not getting a decimal point.

È stato utile?

Soluzione

In C++, a integer divided by a integer will still be a integer (actually any math operation with two integer will provide a integer). So you should either cast them to double first:

midEven = static_cast<double>( *(pScores + midRight) + *(pScores + midLeft) ) / 2;

or divide them by 2.0 which is a double.

midEven = ( *(pScores + midRight) + *(pScores + midLeft) ) / 2.0;

However, there is a potential problem with both approaches, which is that the sum of two scores might exceed the limit of integer. So if you thinks that's likely to happen, a more careful way is:

midEven = ( static_cast<double>(pScores[midRight]) + static_cast<double>(pScores[midLeft]) ) / 2;
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top