这是一项非常简单和常见的练习,虽然我遇到了一个我似乎无法理解的错误,但我无法在任何地方找到解释,因为它可能过于具体。
该程序只是提示用户输入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
答案 0 :(得分:9)
auto minmax = minmax_element(begin(pan), end(pan));
确实找到了min / max,但C ++中的数组索引从0开始。从1索引开始填充int pan[11];
,
big=small=pan[1]; //assigns element to be highest or lowest value; change to pan[0]
for (int i = 1; i < 11; i++){...} // change to i=0
所以pan[0]
将包含1606416304
将考虑的垃圾(在您的情况下,值minmax_element
)。
事实上,读取未初始化的变量是C和C ++中未定义的行为,任何事情都可能发生,尽管大多数时候你只是阅读了那些存储在该内存地址的内容。
如果您使用C ++ 11(现在应该使用),那么您也可以使用range-based for loop来处理煎饼:)
for(auto& pancake: pan) // note the reference, we are reading
{
cin >> pancake; // to read
}
和
for(auto pancake: pan)
{
// further processing here, like
if(pancake < small) { small = pancake;} // etc
}
答案 1 :(得分:7)
你有一个大小为11的数组,但你只做了10个元素的循环,让第一个元素没有初始化。这意味着它包含垃圾(未定义的行为),在这种情况下1606416304,这是最大的,不是吗? =)
从以下位置更改循环:
for (int i = 1; i < 11; i++)
为:
for (int i = 0; i < 11; i++)
std::minmaxelement()然后你想要它工作。
后果:
一般来说,使用能够提供与预期结果不同的功能的一个常见错误是检查您的数据您提供的功能。这样你就知道数据是否有问题或/和功能。在您的情况下,打印阵列会让您明白您的数据不正常!
答案 2 :(得分:2)
您的pan
数组被定义为包含11
个元素,但您只初始化其中的10个元素。值得注意的是,pan[0]
永远不会被初始化,并且会有一些随机值。我猜你的随机值恰好是1606416304。