c ++试图找到数组中每一行的最大值

时间:2018-03-17 01:16:11

标签: c++ arrays max

我不明白为什么没有找到每一行的最大值 这是打印出来的: 输入第一场比赛的得分:7.5 9.3 8.5 7.2 10.0

输入第二场比赛的得分:8.1 7.8 9.2 10.0 7.7

输入第3场比赛的得分:8.5 6.7 8.7 9.4 8.2

输入第4场比赛的分数:7.4 9.3 9.6 8.9 9.1

输入第5场比赛的得分:8.5 7.7 9.7 8.3 8.4

比赛的胜利者#1 10

比赛的胜者#2 10

比赛的获胜者#3 10

比赛的获胜者#4 10

比赛#5 10的获胜者

这是我的代码:

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

const int COLS = 5;
const int ROWS = 5;

int main()
{
    const int scores = 25;

    double competition[scores];

    cout << "Enter the scores of the 1st competition: ";
    cin >> competition[0];
    cin >> competition[1];
    cin >> competition[2];
    cin >> competition[3];
    cin >> competition[4];

    cout << "Enter the scores of the 2nd competition: ";
    cin >> competition[5];
    cin >> competition[6];
    cin >> competition[7];
    cin >> competition[8];
    cin >> competition[9];

    cout << "Enter the scores of the 3rd competition: ";
    cin >> competition[10];
    cin >> competition[11];
    cin >> competition[12];
    cin >> competition[13];
    cin >> competition[14];

    cout << "Enter the scores of the 4th competition: ";
    cin >> competition[15];
    cin >> competition[16];
    cin >> competition[17];
    cin >> competition[18];
    cin >> competition[19];

    cout << "Enter the scores of the 5th competition: ";
    cin >> competition[20];
    cin >> competition[21];
    cin >> competition[22];
    cin >> competition[23];
    cin >> competition[24];

 double table[ROWS][COLS] = {{competition[0], competition[1], competition[2], competition[3], competition[4]},
                             {competition[5], competition[6], competition[7], competition[8], competition[9]},
                             {competition[10], competition[11], competition[12], competition[13], competition[14]},
                             {competition[15], competition[16], competition[17], competition[18], competition[19]},
                             {competition[20], competition[21], competition[22], competition[23], competition[24]}};

    double max = competition[0];

for (int j = 0, k = 1; j < COLS; j++)
{
    cout << "the winner of competition #" << k++ << " ";
    for (int i = 0; i < ROWS; i++)
    {
        if (table[i][j] > max)
        {
            max = table[i][j];
        }
    }
    cout << max << endl;
}
    return 0;
}

1 个答案:

答案 0 :(得分:1)

您需要在发现最大值后重置最大值,最好为0,假设可能达到的最低分数为0.如果您没有重置,则最大值将始终与10相比,并始终返回10。

通常,在尝试查找max时,始终将其初始化为其所具有的数据类型的最小可能值。例如,对于int,这是INT_MIN。您可以在here中找到浮点数和双精度数的等效值。