c++ - 如何比较数组内部的值

标签 c++ arrays

所以我正在编写一个程序,要求用户输入一个人 (1-10) 早餐吃的煎饼数量。该程序必须分析输入并确定哪个人吃的煎饼最多。此外,该程序必须按照所有 10 个人吃的煎饼数量的顺序输出一个列表。到目前为止,我已经编写了获取用户输入的代码和显示数组的代码,但顺序不对。在比较数组中的元素时,我完全迷失了:

int getPancakes();
void displayArray(int theArray[],int sizeOfArray);
void compareArray(int sizeOfArray);
int pancakes[10];
int z = 0;

int main()
{
}

int getPancakes(){
    int y;
    int x = 0;

    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){
    for(int x = 0 ;x < sizeOfArray ; x++){
        ++z;
        cout << "Person " << z << " ate " << pancakes[x] << " pancakes" << endl;
    }
}

那么我该如何指示我的程序比较数组中的元素呢?另外,我如何指示我的程序按顺序打印每个人吃的煎饼数量列表?

最佳答案

为了找出谁吃的煎饼最多,您基本上需要找到数组中最大值的位置。

int findMaxPosition(int array[], int arraySize){
    int maxPosition = 0;     //assume the first element is maximum
    for(int i = 1; i < arraySize; i++)
        if(array[i] > array[maxPosition]) //compare the current element with the known max
            maxPosition = i;   //update maxPosition
    return maxPosition;
}

请注意,这会为您提供第一次出现的最大值。如果元素是唯一的,那就足够了。否则,您应该找到最大值 array[maxPosition],并遍历数组并显示它出现的每个位置。

排序有点复杂。排序算法不是那么简单,我担心如果我给你写一个实现,我也帮不了你。

冒泡排序是最简单的排序算法之一。维基百科 ( http://en.wikipedia.org/wiki/Bubble_sort ) 有一个关于它的详细页面,您应该能够使用那里给出的伪代码来实现它。

关于c++ - 如何比较数组内部的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25769395/

相关文章:

arrays - 在大矩阵中查找许多子矩阵的总和?

javascript数组长度无法在网页中访问

c++ - 将纹理转换为 GL_COMPRESSED_RGBA

c++ - 需要帮助矢量化此代码

python - 重复 1D NumPy 数组中的值 "N"次

c - 等效的常量数组和指针

c++ - 将 char* 分成几个变量

c++ - 具有 3 个 channel 的 nppi 调整大小功能得到奇怪的输出

c++ - 具有不同原型(prototype)的函数指针 vector ,我可以构建一个吗?

c++ - 竞争条件效应