这是一个非常简单且常见的练习,尽管我遇到了一个错误,但我似乎无法理解它,并且无法在任何地方找到解释,因为这可能太具体了。
该程序只是提示用户输入第1到10个人吃了多少煎饼,然后打印出某个人吃的最多的煎饼数量。我的问题是,“手动循环”来排序最大和最小值的工作已经完成,但算法(在这个论坛上强烈推荐使用而不是手动循环)不能正确输出最大值,但对于最小值可以正常工作。
以下是我的代码:
以下是控制台返回的内容:
该程序只是提示用户输入第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
pan[0]
的原因是我不想提示用户输入第0个人吃了多少个煎饼。这样做是否是因为实际情况而不能使用数组呢? - SecureCake<< i <<
改为<< i + 1 <<
。 - AresCaelumpan[0]
开始加上i+1
,非常感谢大家! - SecureCakebegin(pan)+1
调用minmax_element
。 - Saul