首页 > 解决方案 > 如何在c中获取数组的第一个和最后一个值?

问题描述

我在函数中得到以下代码:

    bcc_balancing_status_t balancingStatus;
    uint32_t highestCellvoltage;
    uint32_t lowestCellvoltage;

    uint32_t highestCell;
    uint32_t lowestCell;


    extern uint32_t cell1VoltageUV;
    extern uint32_t cell2VoltageUV;
    extern uint32_t cell3VoltageUV;
    extern uint32_t cell4VoltageUV;
    extern uint32_t cell11VoltageUV;
    extern uint32_t cell12VoltageUV;
    extern uint32_t cell13VoltageUV;
    extern uint32_t cell14VoltageUV;


    int arr[] = {cell1VoltageUV, cell2VoltageUV, cell3VoltageUV, cell4VoltageUV, cell11VoltageUV, cell12VoltageUV, cell13VoltageUV, cell14VoltageUV};
    int n = sizeof(arr)/sizeof(arr[0]);
    bubbleSort(arr, n);
    printf("Sorted array: \n");
    printArray(arr, n);


    highestCellvoltage = //should be the actual value of the cellxVoltageUV ex. 3345688  //
    lowestCellvoltage = //should be the actual value of the cellxVoltageUV ex. 3345688  //

    highestCell = // should be 0 for cell 1, 1 for cell 2 etc.  //
    lowesCell = // should be 0 for cell 1, 1 for cell 2 etc.  //

    printf("voltage of highest cell = %lu \n" highestCellvoltage);
    printf("voltage of lowest cell = %lu \n" lowestCellvoltage);

    if((highestCellvoltage-LowestCellvoltage) > 500){

        BCC_CB_Enable(drvConfig, BCC_CID_DEV1, false);
        balancingStatus = BCC_CB_SetIndividual(drvConfig, BCC_CID_DEV1, highestCell, true, 2);

        printf("currently balancing cell %lu", (highestCell+1));

        return BCC_BALANCING_ON;
        }
        else
        {
            return BCC_BALANCING_OFF;
        }

数组通过函数bubblesort排序,然后我希望它找到数组的第一个和最后一个值,这样我就可以确定这两者之间的区别。printarray 的结果是:

Sorted array: 
3342941 3343399 3343552 3344620 3345688 3345993 3346451 3349960 

我怎样才能找到这个数组的第一个和最后一个值(参见上面代码中的注释)?(解决了)

尚未解决:例如,如果电池 2 (cell2VoltageUV) 具有最高值,我想highestCell设置为 1(因为实际电池计数从 0 开始,而 BCC_CB_Enable 需要一个从 0 到 13 的值)。

标签: c

解决方案


在对数组进行排序,您无法找到元素的原始索引。不可能。

但在对数组进行排序之前,只需执行以下操作:

highestCell = 0;
highestCellvoltage = arr[0];

lowestCell = 0;
lowestCellvoltage = arr[0];

for (int i = 1; i < n; ++i)
{
    if (arr[i] > highestCellvoltage)
    {
        highestCell = i;
        highestCellvoltage = arr[i];
    }
    else if (arr[i] < lowestCellvoltage)
    {
        lowestCell = i;
        lowestCellvoltage = arr[i];
    }
}

// Add bubbleSort(arr, n); here - if needed

之后,您可以对数组进行排序(如果仍然需要)。


推荐阅读