如何找到每行的最大值和最小值

问题描述 投票:-1回答:1

我的练习任务是,如果最小值大于任何其他数组的最大值,则查找数组的索引。如果有多个,则仅打印最低的索引。例如:1 2 3 4 56 7 8 9 10因此输出为2,因为第二行的最小值高于另一行的最大值。但是我一直在寻找[every数组的最小值和最大值,所以我不能继续前进。

int numberOfTowns;
int numberOfDays;
cin >> numberOfTowns >> numberOfDays;
int temperature[100][100];
for (int i = 0; i < numberOfTowns; i++)
{
    int maxValue = temperature[i][0];
    int minValue = temperature[i][0];
    for (int j = 0; j < numberOfDays; j++)
    {
        cin >> temperature[i][j];

        if (temperature[i][j] > maxValue)
            maxValue = temperature[i][j];

        if (temperature[i][j] < minValue)
            minValue = temperature[i][j];

    }
        cout << "Max: " << maxValue << endl;
        cout << "Min: " << minValue << endl;
}
return 0;}

编辑:为澄清起见,numberOfTowns基本上表示行数,而numberOfDays表示列数。我的输入和输出看起来像这样:(3是行数,5是列数)

3 5

10 15 12 10 10

最大:15最低:0

11 11 11 11 20

最大:20最低:0

18 16 16 16 20

最大:20最低:0

所以我的Max正常工作,但我的Min始终为0。有人可以帮忙吗?附注:这是我的第一个问题,我对C ++有点陌生,对不起,如果我做错了什么。

c++ arrays max min
1个回答
0
投票

在将任何内容写入该位置之前,请使用minValue初始化maxValuetemperature[i][0]。而是使用输入值对其进行初始化:

    cin >> temperature[i][0];
    int maxValue = temperature[i][0];
    int minValue = temperature[i][0];
    for (int j = 1; j < numberOfDays; j++)    // start at 1 
    {
        cin >> temperature[i][j];

        if (temperature[i][j] > maxValue)
            maxValue = temperature[i][j];

        if (temperature[i][j] < minValue)
            minValue = temperature[i][j];

    }
© www.soinside.com 2019 - 2024. All rights reserved.