#include <iostream>
usingnamespace std;
struct person {
int num;
int pancakes;
};
int main(){
int min, max, most, least;
person person[10];
for (int n=0; n<10; n++){
cout << "Enter the number of pancake eaten by person #" << n+1 << ": ";
cin >> person[n].pancakes;
}
min = person[0].pancakes;
max = person[0].pancakes;
for (int n=1; n<11; n++){
if(min > person[n].pancakes)
min = person[n].pancakes;
person[n].num = n;
least = person[n].num;
if(max < person[n].pancakes)
max = person[n].pancakes;
person[n].num = n;
most = person[n].num;
}
cout << "The most pancakes were eaten by " << most << ", who ate " << max << ".\n";
}
It runs fine until the last line. It properly displays the number of pancakes inputted, but it just displays "most" as 9. I'm guessing that's because the array goes up to 9, but I can't figure out how to fix it. Any advice?
Yeah, I decided to use struct at the very beginning and by the time I got to the end I didn't really want to go back and change it. Removed the struct and changed it to this:
1 2 3 4 5 6 7 8
for (int n=0; n<10; n++){
if(min > person[n]){
min = person[n];
least = n+1; }
if(max < person[n]){
max = person[n];
most = n+1; }
}
It now works for all possibilities excluding person 1. If it's person 1, it displays -858993460 instead of 1. Why would that happen?
I removed the struct so that won't be a problem anymore. Also, you're right about the number; defining most as 0 gave me 0 instead of that number. I see what I did wrong: min = person[0], so if (min > person[0]) won't ever be true. Changing it to >= solved the problem. Thanks for the help, everybody!
EDIT: The final program, if anybody is interested:
#include <iostream>
usingnamespace std;
int main(){
int min, max, most=0, least, person[10];
for (int n=0; n<10; n++){
cout << "Enter the number of pancake eaten by person #" << n+1 << ": ";
cin >> person[n];
}
min = person[0];
max = person[0];
for (int n=0; n<10; n++){
if(min >= person[n]){
min = person[n];
least = n+1; }
if(max <= person[n]){
max = person[n];
most = n+1; }
}
cout << "The most pancakes were eaten by person #" << most << ", who ate " << max << ".\n";
cout << "The least pancakes were eaten by person #" << least << ", who ate " << min << ".\n";
}