首页 > 解决方案 > 如何找到最大值和最小值

问题描述

我想在一个函数中找到最大值和最小值。我已经尝试过了,但是我只得到了最小值。这是因为代码不是从第一行读取的,并且第一行包含最高值。这是我的代码:

void price (ifstream & infile)
{

   infile.clear();
   infile.seekg(0);

   int year, mall, cafe, expenses;
   infile >> year >> mall >> cafe >> expenses;


   int high_mall {} , high_year {}, high_expenses {};
   int low_mall {} , low_year {}, low_expenses {};

   low_mall = mall;
   low_year = year;
   low_expenses = expenses;

    for (int year {}, mall {}, cafe {}, expenses {};
       nameFile >> year >> mall >> cafe >> expenses; )
    {

        if (expenses > high_expenses)
        {
            high_expenses = expenses;
            high_year = year;
            high_mall = mall;
        }
         if (expenses < low_expenses)
        {
            low_expenses = expenses;
            low_year = year;
            low_mall = mall;
        }
    }

        cout << "Highest expenses are " << high_expenses << "at" << high_year << endl;
        cout << "Total mall that year are " << high_mall << endl ;
        
        cout << "Lowest expenses are " << low_expenses << "at" << low_year << endl;
        cout << "Total mall that year are " << low_mall << endl ;

    }

这是我的代码。我试图删除第一个内联并获得最大值但最小值变为 0。有谁知道如何解决它?我在想std::numeric_limits。但是我可以不使用它来解决这个问题吗?

标签: c++

解决方案


因为 的初始值low_expenses为零,所以您永远不会找到任何费用较低的年份,除非费用为负数。您应该将您low_expenses的初始化为最大可能的整数,如下所示:

low_expenses{ std::numeric_limits<int>::max() };

如果费用可能为负数,初始化high_expenses为可能的最低值也将有所帮助:

high_expenses{ std::numeric_limits<int>::min() };

您需要包含<limits>标题才能使其正常工作。

此外,正如 WhozCraig 指出的那样,这条线

infile >> year >> mall >> cafe >> expenses;

将丢弃一行输入。这不是必要的。您可以将low_...and初始化high_...为第一行的值,但是您可能还必须检查第一个 I/O 操作是否成功。(如果没有行)


推荐阅读