在For循环数组C ++中找到最大和最小值的值

时间:2019-03-28 02:24:25

标签: c++

好的,我有我的代码(如下所示),该代码基本上获得了全年的最大和最小温度值。现在可以了,但是我遇到麻烦的地方是想出一个解决方案,当在数组中找到最大值时,将增量值“ j”放出来。我需要这样做是因为该程序的主要目标是输出找到最大值和最小值的月份。而且我已经有一个用此代码编写的函数,它将递增的值转换为字符串月份。

TLDR: 我需要找出如何知道我的程序以什么值“ j”找到最大值和最小值。

因此,如果你们能对我如何实现这一目标提供任何见解,那将是非常棒的!

     //Gathering Largest Temperature:
    for(int j = 0; j < size; j++)
    {
        if(yearData[j].highTemperature > highestTemperature)
           highestTemperature = yearData[j].highTemperature;
    }

    //Gathering Smallest Temperature:
    for(int j = 0; j < size; j++)
    {
        if(yearData[j].lowTemperature < lowestTemperature)
            lowestTemperature = yearData[j].lowTemperature;
    }

2 个答案:

答案 0 :(得分:1)

//Gathering Largest Temperature:
auto highestTemperature = yearData[0].highTemperature;
int highestTemperatureDate = 0;
for(int j = 0; j < size; j++)
{
    if(yearData[j].highTemperature > highestTemperature)
    {
       highestTemperature = yearData[j].highTemperature;
       highestTemperatureDate = j;
    }
}

//Gathering Smallest Temperature:
auto lowestTemperature = yearData[0].lowTemperature;
int smallestTemperatureDate = 0;
for (int j = 0; j < size; j++)
{
    if (yearData[j].lowTemperature < lowestTemperature)
    {
        lowestTemperature = yearData[j].lowTemperature;
        smallestTemperatureDate = j;
    }
}

我为最小和最高温度添加了一个整数

答案 1 :(得分:1)

使用std,您可以这样做:

//Gathering Largest Temperature:
auto max = std::max_element(std::begin(yearData), std::end(yearData),
                            [](const auto& lhs, const auto& rhs){
                                return lhs.highTemperature < return rhs.highTemperature;
                            });

auto max_index = std::distance(std::begin(yearData), max);

// Gathering Smallest Temperature:
auto min = std::min_element(std::begin(yearData), std::end(yearData),
                            [](const auto& lhs, const auto& rhs){
                                return lhs.lowTemperature < return rhs.lowTemperature;
                            });
auto min_index = std::distance(std::begin(yearData), min);
相关问题