【问题标题】:how to call an element from an array depends on the condition如何从数组中调用元素取决于条件
【发布时间】:2022-01-02 05:45:55
【问题描述】:

我必须编写一个函数,根据客户喜欢的顺序(最低、次低等)调用最低价格,但我很难尝试从数组中调用正确的元素。

int lowestPrice(int array[], int size, int order){

int tempArray[size];

for(int i = 0; i < size; i++){
    int swapped = 0;

    for(int j = 0; j < size - i - 1; j++){
        
        if(array[i] > array[i+1]){
            int temp = array[i];
            array[i] = array[i+1];
            array[i+1] = temp;

            swapped = 1;
        }

        int j=0;
        
        for (int i = 0; i < size - 1; i++){
        
            if (array[i] != array[i+1]){
                tempArray[j] = array[i];
            }j++;
        } tempArray[j] = array[i - 1];

    }
        if (swapped == 0){
            
            for (int i = 0; i < size; i++){
                printf("%d\t", array[i]);

            }break;
        }
}    



}

【问题讨论】:

标签: arrays c


【解决方案1】:

如果您的条件符合我的猜测,那么您可以这样做:

int lowestPrice(int array[], int size, int order){
// if you want to keep the same order in your initial array copy it in a new one:
// you can do that with memcpy as well but i asume you can't...
    int tempArray[size];
    for (size_t i = 0; i < size; i++)
        tempArray[i] = array[i];
// Then sort it :
    for (size_t i = 0; i < size; i++)
        for (size_t j = i; j < size; j++)
            if (tempArray[j] < tempArray[i]) {
                int tmp = tempArray[i];
                tempArray[i] = tempArray[j];
                tempArray[j] = tmp;
            }
// Return the one you want with order (order from the lowest to the highest):
    return tempArray[order];
}

【讨论】:

    猜你喜欢
    • 2020-06-03
    • 2012-03-13
    • 1970-01-01
    • 1970-01-01
    • 2011-05-25
    • 2012-01-02
    • 1970-01-01
    • 2023-01-29
    • 2020-08-28
    相关资源
    最近更新 更多