这是一个非常简单且常见的练习,尽管我遇到了一个错误,但我似乎无法理解,并且在任何地方都找不到解释,因为它可能太具体了。
该程序只是提示用户输入第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
auto minmax = minmax_element(begin(pan), end(pan));
确实找到了最小/最大值,但是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(现在您应该使用),那么您也可以使用基于范围的循环处理煎饼:)
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
}
您的数组是11号的数组,但是您只循环超过10个元素,而第一个元素则是非初始化的。这意味着它包含垃圾(未定义的行为),在这种情况下,1606416304,最大,不是吗?=)
从:
更改循环for (int i = 1; i < 11; i++)
to:
for (int i = 0; i < 11; i++)
std :: minmaxelement()然后随心所欲。
后果:
通常,在处理与预期结果不同的功能时,一个常见的错误是检查您的数据您提供该功能。这样,您知道数据是否有问题或/和功能。在您的情况下,打印阵列会让您了解数据不好!
您的pan
数组定义为具有11
元素,但您仅初始化其中10个。值得注意的是,pan[0]
永远不会初始化,并且会有一些随机值。我猜您的随机价值恰好是1606416304。