Finding the Index of the Min/Max Value in an Array C++

时间:2015-12-10 01:20:38

标签: c++ arrays

So I'm trying to figure out how to get the min/max value of an array, and get the corresponding index value. I also am not sure how to call that function in my main function. My trouble is in the final part of the problem statement. I put it in block quotes. I started to make the getHighest function, but I don't know where to go or if I am even doing it right. Any help appreciated.

//Write a program that uses a structure to store the following information, for 
//a particular month, at the local airport:
// Total number of planes that landed
// Total number of planes that departed
// Greatest number of planes that landed in a given day that month
// Least number of planes that landed in a given day that month
//The program should have an array of twelve structures to hold travel information 
//for the entire year. The program should prompt the user to enter data for each 
//month. Once all data is entered, the program should calculate and output the average 
//monthly number of landing planes, the average monthly number of departing planes, 
//the total number of landing and departing planes for the year, and 

the greatest and least number of planes that landed on any one day (and which month it occurred in).

#include <iostream>
#include <iomanip>
using namespace std;

const int NUM_MONTHS = 2;

struct AirportData
{
    int planesLanded;
    int planesDeparted;
    int mostPlanesLanded;
    int leastPlanesLanded;
};

// Function Prototypes
void getHighest(int AirportData array[], int size);
void getLowest();
double getLandingAverage(int landedSum, int NUM_MONTHS);
double getDepartedAverage(int departedSum, int NUM_MONTHS);

int main()
{
    int landedSum = 0;
    int departedSum = 0;
    int totalPlanes = 0;
    double average = 0.0;
    AirportData travelInformation[NUM_MONTHS];

    // Get user input
    for(int i = 0; i < NUM_MONTHS; i++)
    {
        cout << "How many planes landed in month " << i + 1 << " ? ";
        cin >> travelInformation[i].planesLanded;

        cout << "How many planes departed in month " << i + 1 << " ? ";
        cin >> travelInformation[i].planesDeparted;

        cout << "What is the greatest number of planes that landed "
             << "on a given day in month " << i + 1 << " ? ";
        cin >> travelInformation[i].mostPlanesLanded;

        cout << "What is the least number of planes that landed "
             << "on a given dey in month " << i + 1 << " ? ";
        cin >> travelInformation[i].leastPlanesLanded;

        cout << endl;
    }

    // Calculate the Sum
    for(int i = 0; i < NUM_MONTHS; i++)
    {
        landedSum = landedSum + travelInformation[i].planesLanded;
        departedSum = departedSum + travelInformation[i].planesDeparted;
    }

    // Calculate the total amount of planes landed and departed YTD
    totalPlanes = landedSum + departedSum;

    // Output the results
    cout << endl;
    cout << "The average number of monthly landing planes is: "
             << getLandingAverage(landedSum, NUM_MONTHS) << endl;
    cout << "The average number of monthly departed planes is: "
             << getDepartedAverage(departedSum, NUM_MONTHS) << endl;
    cout << "Landing and Departing Planes this Year: " << totalPlanes << endl;


    return 0;
}

// getHighest() function - Get's the most planes landed on a given day and outputs


    void getHighest(AirportData array[], int size)
{
    int highest = 0;
    int maxIndex = 0;

    for(int i = 0; i < NUM_MONTHS; i++)
    {
        if(array[i].mostDailyLanded > highest)
        {
            highest = array[i].mostDailyLanded;
            maxIndex = i + 1;
        }
    }
    cout << "The greatest number of planes that landed on a day was " << highest
         << " in Month " << maxIndex << endl;
}

// getLowest() function - Get's the least planes landed on a given day and outputs
void getLowest(AirportData array[], int size)
{
    int lowest = array[1].leastDailyLanded;
    int maxIndex = 0;

    for(int i = 0; i < NUM_MONTHS; i++)
    {
        if(array[i].leastDailyLanded < lowest)
        {
            lowest = array[i].leastDailyLanded;
            maxIndex = i + 1;
        }
    }
    cout << "The least number of planes that landed on a day was " << lowest
         << " in Month " << maxIndex << endl;
}


// getLandingAverage() function - Get's the average monthly planes landed
double getLandingAverage(int landedSum, int NUM_MONTHS)
{
    return landedSum/NUM_MONTHS;
}

// getDepartedAverage() function - Get's the average monthly planes departed
double getDepartedAverage(int departedSum, int NUM_MONTHS)
{
    return departedSum/NUM_MONTHS;
}

3 个答案:

答案 0 :(得分:1)

您必须先创建一个数组,然后将每个月的值复制到其中,因此在您的程序环境中,可能更容易进行函数签名

maxIndex = 1;

除此之外,您前进的方式是一种简单的方法来找出您需要的东西。您从最低值开始,遍历所有元素,如果找到更高的值,则记录它是什么,以及找到它的月份。唯一的错误是您指定maxIndex = i + 1;什么时候应该是Webpack -w

答案 1 :(得分:0)

我认为你可以通过添加两个阵列来解决它,着陆和离开。

int landed[NUM_MONTS]

然后在for循环中,您可以添加

landed[i] = travelInformation[i].planesLanded;

然后你可以调用函数getHighest(landed, NUM_MONTHS)来产生你想要的输出。

并将getHighest函数中的maxIndex赋值更改为此

maxIndex = i + 1;

或者我错了,你的问题不是很清楚。

答案 2 :(得分:0)

恕我直言,在较低级别的功能中处理输出是不好的做法。

我会使用以下签名:

public class MatlabMainWindow extends AppCompatActivity {

private Button treeButton;
private Button positionButton;
private TextView textViewTree;
private PositionDetector positionDetector;
private String treeHolder;
private Classifier j48ClassifierHolder;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_matlab_main_window);

    treeButton = (Button) findViewById(R.id.button_tree);
    positionButton = (Button) findViewById(R.id.button_position);
    textViewTree = (TextView) findViewById(R.id.textView_tree);

    BinaryHttpRequest binaryHttpRequest = new BinaryHttpRequest(....)

    Volley.newRequestQueue(MatlabMainWindow.this).add(binaryHttpRequest);

    treeButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            BackgroundTask task = new BackgroundTask(MatlabMainWindow.this);
            task.execute();
        }
    });

    positionButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            try {
                String positionString = positionDetector.calculateThePosition();

                AlertDialog.Builder alert = new AlertDialog.Builder(MatlabMainWindow.this);
                alert.setTitle("Position Prediction");
                alert.setMessage(positionString);
                alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub

                    }
                });
                alert.show();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });

}

private class BackgroundTask extends AsyncTask<Void, Void, Void> {

    private ProgressDialog dialog;

    public BackgroundTask(MatlabMainWindow activity) {
        dialog = new ProgressDialog(activity);
    }

    @Override
    protected void onPreExecute() {
        dialog.setMessage("Doing something, please wait.");
        dialog.show();
    }

    @Override
    protected void onPostExecute(Void result) {
        try {
            treeHolder = positionDetector.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        textViewTree.setMovementMethod(new ScrollingMovementMethod());
        textViewTree.setText(treeHolder);
        if (dialog.isShowing()) {
            dialog.dismiss();
        }


    }

    @Override
    protected Void doInBackground(Void... params) {

        positionDetector = new PositionDetector();
            try {
        // reading the binary file here 
                positionDetector.getTrainData();
            } catch (Exception e) {
                e.printStackTrace();
            }

            return null;
    }
}
}

代码可能变成:

int getHighest(int AirportData array[], int size, int *month);

这样,你从main调用它,只在main中输出。如果您以后将程序更改为GUI程序,则计算例程将不必更改。