简体   繁体   中英

Need to find the minimum value of a 4x2 array while ignoring the diagonal

I need to find the lowest value in an array that isn't in the main diagonal, I have written some code but it seems to pick either the second or the last value only (depending on which one is the lowest).

here is my code:

#include<iostream>
using namespace std;
int main()
{
    int arr[4][2];
    int Min,i,j;
    cout<<"Type 8 numbers";
    for (i=0;i<4;i++)
    {
        for (j=0;j<2;j++)
        {
            cin>>arr[i][j];
            Min=arr[0][1];
            if(i!=j and Min > arr[i][j])
            {
                Min=arr[i][j];
            }
        }
    }
    cout<<"The values of the array are: \n";
    for (i=0;i<4;i++)
    {
        cout<<"\n";
        for (j=0;j<2;j++)
        {
            cout<<arr[i][j]<<"\t";
        }
    }
    cout<<"The lowest value is: "<<Min;
}

If I type 1-8 the returned value is 2, if I type 8-1 the returned Value is 1, in both of these cases the code is working as I intended, but if I type something like 8,6,4,1,2,3,4,5, the lowest value is returned as 5, I'm very new to coding and would appreciate any help.

The line

Min=arr[0][1];

is bad because

  • It reads uninitialized arr[0][1] when i = 0, j = 0 .
  • It writes arr[0][1] to Min unconditionally, even if current Min is smaller than that.

Instead of this:

Min=arr[0][1];
if(i!=j and Min > arr[i][j])
{
    Min=arr[i][j];
}

This will work, for example:

if(i!=j and ((i==0 and j==1) or Min > arr[i][j]))
{
    Min=arr[i][j];
}

Your Min=arr[0][1] line is inside both loops, which means each time when you are trying to compare Min and the current element arr[i][j] , you just threw away whatever smallest value stored in Min and replaced it with arr[0][1] .

Hence the code as you have written returns either the last number or arr[0][1] , whichever is smaller.

You should really only initialise this Min once before your loops begin. ie

Min = arr[0][1]
for(i = 0; i < 4;i++)
{
    for(j = 0; j < 2; j++)
    {
     // Compare Min and arr[i][j] and reassign the smaller one to Min if i != j
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM