【发布时间】:2017-08-01 04:49:13
【问题描述】:
这是一个非常简单且常见的练习,尽管我遇到了一个我似乎无法理解的错误,并且我无法在任何地方找到解释,因为它可能太具体了。
程序只是提示用户输入第 1 到第 10 个人吃了多少煎饼,然后打印出某人吃的最多煎饼数量。我的问题是排序最大和最小值的“手工循环”有效,但是算法(在这个论坛上强烈推荐使用而不是手工循环)没有打印出正确的 最大值,但适用于最小。
这是我的代码:
void pancakes() {
int pan[11];
int small, big;
for (int i = 1; i < 11; i++) // counts to 11-1 and prompts user for pancakes
// eaten by person 1==>10
{
cout << "How many pancakes did person " << i << " eat?\n";
cin >> pan[i];
}
big = small = pan[1]; // assigns element to be highest or lowest value
for (int i = 1; i < 11; i++) {
if (pan[i] > big) // compare biggest value with current "big" element
{
big = pan[i];
}
if (pan[i] < small) // compares smallest value with current "small" element
{
small = pan[i];
}
}
cout << "The person who ate the most pancakes ate " << big << " of them."
<< endl; // prints biggest value
cout << "The person who ate the least pancakes ate " << small << " of them."
<< endl; // prints smallest value
auto minmax = minmax_element(begin(pan), end(pan));
cout << "min element " << *(minmax.first) << "\n";
cout << "max element " << *(minmax.second) << "\n";
}
这是控制台返回的内容:
How many pancakes did person 1 eat?
45
How many pancakes did person 2 eat?
64
How many pancakes did person 3 eat?
7
How many pancakes did person 4 eat?
34
How many pancakes did person 5 eat?
87
How many pancakes did person 6 eat?
45
How many pancakes did person 7 eat?
89
How many pancakes did person 8 eat?
32
How many pancakes did person 9 eat?
55
How many pancakes did person 10 eat?
66
The person who ate the most pancakes ate 89 of them.
The person who ate the least pancakes ate 7 of them.
min element 7
max element 1606416304
【问题讨论】:
标签: c++ arrays algorithm loops sorting