我想找出一个函数中的最大值和最小值。我试过了,但我只得到了最小的价值。这是因为代码不是从第一行读取的,而第一行包含最高值。这是我的代码:
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
。但是我能不使用它来解决这个问题吗?
4条答案
按热度按时间ozxc1zmp1#
因为
low_expenses
的初始值为零,所以你永远找不到任何一年的费用更低,除非费用是负的。你应该初始化你的low_expenses
为最大可能的整数,如下所示:如果开销可以为负,那么将
high_expenses
初始化为最低可能值也会有所帮助:您需要包含
<limits>
头才能工作。此外,正如WhozCraig所指出的,这条线
将丢弃一行输入。这是不必要的。您可以将
low_...
和high_...
初始化为第一行的值,但随后可能还必须检查第一个I/O操作是否成功。(如果没有行)t5fffqht2#
初始化你的最高和最低的内容后,初始读取之前,进入循环读取其余部分。
示例:
k97glaaz3#
一个好的做法是使用标准库已经提供的thin。std::minmax_element正是你所需要的。
也可以将stream转换为某些特定数据的迭代器:std::istream_iterator。
这两件事可以组合成下面的代码:
https://godbolt.org/z/EMvjx5Yrq
9w11ddsr4#
我试了一下,效果很好