从二维数组中查找最小值和最大值

时间:2017-05-20 18:08:00

标签: c++ multidimensional-array

我的实际问题是如何从随机数组中找到最小值和最大值?,我已尝试了很多不同的逻辑,我已经通过下面提到的这些链接,但无法获得重新连接,任何指导将是值得欣赏的

https://www.youtube.com/watch?v=yes0HMZWxUo&t=447s Put a multidimensional array into a one-dimensional array

#include<iostream>
#include<cstdlib>
#include<conio.h>

void populateArray();
void displayArray();
void findMaxMinNumber(int[5][5]);

main(){
    system("cls");
    int rows,columns = 5;
    displayArray();
}

void populateArray(){

    int randomNumber;
    int minMax[5][5];

    for(int rowCount = 0; rowCount < 5; rowCount++){    

    for(int columnCount = 0; columnCount < 5; columnCount++){
        randomNumber = rand() % 100 + 1;
        cout<<randomNumber;
        minMax[rowCount][columnCount] = randomNumber;

        if(randomNumber < 10){
            cout<<"      ";
        }
        else if(randomNumber >= 10){
            cout<<"     ";
        }   
        }   
        cout<<endl;
    }
findMaxMinNumber(minMax);
}
void displayArray(){
    cout<<"Displaying array's data..."<<endl;
    cout<<"------------------------------"<<endl;
    populateArray();
}
void findMaxMinNumber(int arr[5][5]){

    int rowMax = 0;
    int colMax = 1;
    int rowMin = 0;
    int colMin = 1;
    cout<<endl;
    for(int i = 0; i < 5; i++){
        rowMax++;
        rowMin++;
    for(int j = 0; j < 5; j++){
        if(arr[i][j] < arr[rowMax][colMax]){
            //cout<<endl<<arr[i][j];
            rowMax = i;
            colMax = j;
        }
        if(arr[i][j] > arr[rowMin][colMin]){
            rowMin = i;
            colMin = j;
        }
        colMax++;
        colMin++;
    }

}
cout<<endl<<"The max is :"<<arr[rowMax][colMax];
cout<<endl<<"The min is :"<<arr[rowMin][colMin];
}

2 个答案:

答案 0 :(得分:1)

void findMaxMinNumber(int arr[5][5]){
  int* start = &arr[0][0];

  cout<<endl<<"The max is :" << *std::max_element(start, start + 5*5);
  cout<<endl<<"The min is :" << *std::min_element(start, start + 5*5);
}

答案 1 :(得分:0)

void fillUpArray(int newArray[5][5])
{
    for (int i = 0; i < 5; ++i)
    {
        for (int j = 0; j < 5; ++j)
        {
            int randomNumber = rand() % 100 + 1;
            printf("Random number[%d][%d]: %d\n", i, j, randomNumber);
            newArray[i][j] = randomNumber;
        }
    }
}

void printMinimumMaximum(int myArray[5][5])
{
    int minimum = myArray[0][0];
    int maximum = myArray[0][0];

    for (int i = 0; i < 5; ++i)
    {
        for (int j = 0; j < 5; ++j)
        {
            if (myArray[i][j] < minimum)
            {
                minimum = myArray[i][j];
            }
            if (myArray[i][j] > maximum)
            {
                maximum = myArray[i][j];
            }
        }
    }

    printf("Minimum: %d\n", minimum);
    printf("Maximum: %d\n", maximum);
}

int main()
{
    int minMax[5][5];
    fillUpArray(minMax);
    printMinimumMaximum(minMax);
    return 0;
}