C ++使用数组的中值函数问题

时间:2017-04-06 22:55:09

标签: c++ arrays function median

我无法使此功能正常工作。我正在尝试编写一个中位函数,它接受用户输入的数组和大小,验证它是否正确,然后对其进行排序并显示中位数和排序数组。我尝试了几种不同的东西,无论我尝试什么,我都无法使这个程序工作。任何帮助,将不胜感激。非常感谢你。

#include <iostream>
#include <iomanip>


using namespace std;

double median(int n[], int size);

int main(int argc, char** argv) {
    cout << "Calculate The Median of an Array" << endl;
    cout << "---------------------------------" << endl;
    int size, n;
    cout << "Array Size (Maximum is Ten)? ";
    cin >> size;
    if (size > 10 || size < 0) {
        cout << "Invalid size. Please Re-enter." << endl;
    };
    cout << "Array Contents? ";
    cin >> n;
    if ([n] != size) {
        cout << "Invalid Array. Please Re-enter. " << endl;
    };
    median(n, size);
    return 0;
};

double median(int n[], int size) {
     // Allocate an array of the same size and sort it.

    double* dpSorted = new double[size];
    for (int i = 0; i < size; ++i) {
        dpSorted[i] = n[i];
    };

    for (int i = size - 1; i > 0; --i) {
        for (int j = 0; j < i; ++j) {
            if (dpSorted[j] > dpSorted[j+1]) {
                double dTemp = dpSorted[j];
                dpSorted[j] = dpSorted[j+1];
                dpSorted[j+1] = dTemp;
            };
        };
    };

    // Middle or average of middle values in the sorted array.
    int median = 0;
    if ((size % 2) == 0) {
        median = (dpSorted[size/2] + dpSorted[(size/2) - 1])/2.0;
    } 
    else {
       median = dpSorted[size/2];
    };

    cout << "Median of the array " << dpSorted << "is " << median << endl;
};

我收到以下错误,我无法弄清楚如何修复它们。

34  16  C:\Users\ryanw\Desktop\C++\Labs\Lab 6\main.cpp  [Error] invalid 
conversion from 'int' to 'int*' [-fpermissive]

18  8   C:\Users\ryanw\Desktop\C++\Labs\Lab 6\main.cpp  [Note] initializing 
argument 1 of 'double median(int*, int)'

2 个答案:

答案 0 :(得分:0)

您正在将{int}传递给median

median(n, size);

这条线几乎肯定没有你认为的那样做

if ([n] != size)

我有点担心你的编译器接受它作为有效的语法。

您需要更改main以获取n的整数集合,以将其传递到中位数。

评论者建议使用向量而不是数组是正确的,原始数组永远不会在c ++中使用正确的集合类型。请注意,数组作为与C互操作的代码中的参数出现,它们被视为指针

#include <algorithm>
#include <iterator>
#include <vector>

int median(const vector<int> & numbers); // takes a reference to a vector of ints, and ensures the vector isn't changed

int main(int argc, char** argv) {
    cout << "Calculate The Median of some integers" << endl;
    cout << "-------------------------------------" << endl;
    vector<int> numbers;
    for(int n; cin >> n;) { numbers.push_back(n); }
    int result = median(numbers);
    cout << "The Median of the numbers is " << result << endl;
    return 0;
};

int median(const vector<int> & numbers)
{
    int size = numbers.size(); // vectors know how many elements they have
    vector<int> copy = numbers; // we copy the vector into a local, that we will modify later, leaving numbers unchanged
    sort(copy.begin(), copy.end()); // sort is a std:: function
    return (size % 2) ? // this is a single expression that chooses from two subexpressions. It is called (the) "ternary operator" (ternary being of three parameters)
        copy[size/2] : // even
        (copy[size/2] + copy[(size/2) - 1])/2; // odd
}

答案 1 :(得分:0)

我将解释内容作为代码中的注释。这是阵列版本。我保持尽可能接近OP的来源。

#include <iostream>
#include <iomanip>


using namespace std;

double median(int n[], int size);

int main() { // the parameters asre not being used. You can safely leave them out.
    cout << "Calculate The Median of an Array" << endl;
    cout << "---------------------------------" << endl;
    unsigned int size; // unsigned disallows negative numbers. Lest testing required
    int n[10]; // n is an array of 10 elements
    cout << "Array Size (Maximum is Ten)? ";
    cin >> size;
    while (size > 10) { // repeat until user provides a valid size
        cout << "Invalid size. Please Re-enter." << endl;
        cin >> size;
    };
    // the above loop will be an infinite loop if the user types in a value
    // that cannot be converted into an integer.

    cout << "Array Contents? ";
    for (unsigned int index = 0; index < size; index++)
    {
        cin >> n[index];
    }

    // don't need to test the size. This is ensured by the for loop. Mostly
    // for now we are ignoring the simple problem: "what if the user inputs
    // a value that is not an integer?
    median(n, size);
    return 0;
}// don't need ; after function.

double median(int n[], int size) {
     // Don't need an array of doubles. Ignoring it.

    // assuming the logic here is correct. If it isn't, that's a different
    // topic and another question.
    for (int i = size - 1; i > 0; --i) {
        for (int j = 0; j < i; ++j) {
            if (n[j] > n[j+1]) {
                int dTemp = n[j];
                n[j] = n[j+1];
                n[j+1] = dTemp;
            };
        };
    };

    // Middle or average of middle values in the sorted array.
    double result = 0; //reusing an identifier is a dangerous business. Avoid it.
    if ((size % 2) == 0) {
        result = (n[size/2] + n[(size/2) - 1])/2.0;
    }
    else {
        result = n[size/2];
    };

    cout << "Median of the array is " << result << endl;

    // it's harder to print out an array than I think it should be.
    // Leaving it out for now

    // Other than main, a function with a return type must ALWAYS return.
    return result;
}

使用std::vector和其他图书库魔法:

#include <iostream>
#include <iomanip>
#include <vector>
#include <algorithm>


// using namespace std; generally should avoid this

// moving median up here so forward declaration isn't needed
double median(std::vector<int> &n) { //don't need size. Vector knows how big it is
    std::sort(n.begin(), n.end()); // use built-in sort function

    double result = 0; 
    auto size = n.size();
    if ((size % 2) == 0) {
        result = (n[size/2] + n[(size/2) - 1])/2.0;
    }
    else {
        result = n[size/2];
    };

    // since this function calculates and returns the result, it shouldn't 
    // also print. A function should only do one thing. It make them easier 
    // to debug and more re-usable
    return result;
}


int main() {
    // can chain couts into one
    // endl is more than just a line feed and very expensive. Only use it
    // when you need the message to get out immediately
    std::cout << "Calculate The Median of an Array\n" <<
                 "---------------------------------\n" <<
                 "Array Size (Maximum is Ten)? " << std::endl;
    unsigned int size;
    std::cin >> size;
    while (size > 10) {
        // here we use endle because we want he user to see the message right away
        std::cout << "Invalid size. Please Re-enter:" << std::endl;
        std::cin >> size;
    };

    std::vector<int> n(size);

    std::cout << "Array Contents? " << std::endl;
    for (int & val: n) // for all elements in n
    {
        std::cin >> val;
    }

    std::cout << "Median of the array is " << median(n) << std::endl;

    return 0;
}