简体   繁体   English

需要在忽略对角线的情况下找到 4x2 数组的最小值

[英]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.如果我输入 1-8,则返回值为 2,如果我输入 8-1,则返回值为 1,在这两种情况下,代码都按我的预期工作,但如果我输入类似 8、6、4、1 的内容,2,3,4,5,最小值返回为 5,我对编码非常陌生,希望能提供任何帮助。

The line线

Min=arr[0][1];

is bad because不好,因为

  • It reads uninitialized arr[0][1] when i = 0, j = 0 .i = 0, j = 0时,它读取未初始化的arr[0][1]
  • It writes arr[0][1] to Min unconditionally, even if current Min is smaller than that.它无条件地将arr[0][1]写入Min ,即使当前Min小于该值。

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] .您的Min=arr[0][1]行在两个循环内,这意味着每次当您尝试比较 Min 和当前元素arr[i][j]时,您只需丢弃存储在Min和将其替换为arr[0][1]

Hence the code as you have written returns either the last number or arr[0][1] , whichever is smaller.因此,您编写的代码返回最后一个数字或arr[0][1] ,以较小者为准。

You should really only initialise this Min once before your loops begin.你真的应该只在循环开始之前初始化这个Min一次。 ie 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
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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