所以我在做练习,我必须要求用户输入 10 个人吃的煎饼数量,打印出谁吃的煎饼最多,然后从最大到最小组织列表,基本上我必须打印出来:
第3人:吃了10个煎饼,第5人:吃了9个煎饼,第8人:吃了8个煎饼
但是使用冒泡排序后,我无法将人与正确的值匹配,因为冒泡排序会交换他们!有谁知道有什么方法可以解决这个问题吗?例如,是否有另一种方法可以在不使用冒泡排序的情况下组织数组中的值?
void getPancakes()
{
int x = 0;
int temp;
for(int y = 0; y < 10; y++)
{
++x;
cout << "How many pancakes did person " << x << " eat?" << endl;
cin >> pancakes[y];
}
}
void displayArray(int theArray[],int sizeOfArray)
{
int temp;
int i,j;
int q = 10;
for(i = 0; i <= sizeOfArray - 1 ; i++)
{
for(j = i+1 ; j < sizeOfArray ; j++)
{
if(theArray[i] < theArray[j])
{
temp = theArray[i];
theArray[i] = theArray[j];
theArray[j] = temp;
}
}
}
cout << endl;
for(i = 0; i < 10; i++)
cout << "Person " << i+1 << " ate " << theArray[i] << " pancakes" << endl;
}
最佳答案
就像科迪所说,您必须存储这两个值。正如@HgMs 所指出的,您可以创建一个类或一个struct
,它是一个仅包含公共(public)数据成员的类。这是一个例子:
struct person{
int id;
int pancakes;
};
int main(){
const int totalPeople = 10;
person personArray[totalPeople];
for (int i = 0; i < totalPeople; ++i){
cout << "How many pancakes did person " << i << " eat? ";
personArray[i].id = i;
cin >> personArray[i].pancakes;
}
for (int i = 0; i < totalPeople; ++i){
cout << "id: " << personArray[i].id << "\t" << "Pancakes eaten: " << personArray[i].pancakes << endl;
}
return 0;
}
然后,您可以迭代该数组并使用 '.'
访问该属性来查看每个人吃过的煎饼数量。
编辑:冒泡排序可以很好地工作。
关于c++ - 如何打印数组元素的索引号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25800268/