c++ - 如何找到最大值和最小值
问题描述
我想在一个函数中找到最大值和最小值。我已经尝试过了,但是我只得到了最小值。这是因为代码不是从第一行读取的,并且第一行包含最高值。这是我的代码:
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
。但是我可以不使用它来解决这个问题吗?
解决方案
因为 的初始值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 操作是否成功。(如果没有行)
推荐阅读
- javascript - 在 React with ES6 中,constructor(prop) 不会引发错误。为什么?
- r - R中迭代更改集合中的矩阵的方法
- python - 如何将 bash 脚本导出到 python?
- sql - 如何根据字段中的值截断或添加小数 - SQL server
- go - golang 中的 smtp 问题(恐慌,信号 SIGSEGV:分段违规)
- java - 如何检查链接是否是使用 Java 的下载链接?
- php - 条件参数和返回类型声明(又名类型提示)
- r - 为什么我在 na.fail.default(list(doc.class = c(3L, 1L...missing values in object) 中出现错误
- mysql - MySQL选择随机整数
- api - 您可以在 Dialogflow API v2.0 上创建自己的客户端吗?