ETH官方钱包

前往
大廳
主題

[OJ練習(xí)] 10107 Median Num 順便更新封面圖ㄌ(我婆ouo)

テリ君(桃夫模式) | 2023-02-23 13:27:40 | 巴幣 12 | 人氣 246

10107(3/5)

#include <stdio.h>
#include <stdlib.h>
#include <math.h> //requires math.h to get the floor num

struct sortMaxMin{
    float max, min;
};
// def sturct

typedef struct sortMaxMin Struct;

// make sort sturct

Struct sort(float a, float b){
    Struct s;
    if (a > b){
        s.max = a;
        s.min = b;
    }
    else{
        s.max = b;
        s.min = a;
    }
    
    return s;
}

int main(){
    int i = 0;
    Struct result;
    float *a, sum = 0;
    a = (float*)malloc(sizeof(float)); // actually idk why only need one space?
    
    
    // i = 0 just print, i > 0 bubble sort then print
    while(scanf("%f", (a + i)) != EOF){
        if(i == 0){
            printf("%.0f\n", *(a + i));
        }
        else if((i + 1) % 2 != 0){
            for(int j = 0; j < i; j++){
                for(int k = 0; k < i - j; k++){
                    result = sort(*(a + k), *(a + k + 1));
                    *(a + k) = result.min;
                    *(a + k + 1) = result.max;
                }
            }
        
            sum = floor(*(a + ((i + 1) / 2)));
            printf("%.0f\n", sum);
        }
        else if((i + 1) % 2 == 0){
            for(int j = 0; j < i; j++){
                for(int k = 0; k < i - j; k++){
                    result = sort(*(a + k), *(a + k + 1));
                    *(a + k) = result.min;
                    *(a + k + 1) = result.max;
                }
            }
        
            sum = floor((*(a + ((i - 1)/ 2)) + *(a + ((i + 1) / 2))) / 2);
            printf("%.0f\n", sum);
        }
        i++;
        a = realloc(a, (i + 1) * sizeof(float));
    }
    
    free(a);
    
    return 0;
}

簡單來說就是找出中位數(shù),若中位數(shù)非整就向下取整。
主要是學(xué)了新東西,因為c沒辦法像py那樣直接爽爽回傳兩個值以上,所以剛剛學(xué)會了要先用struct去定義要回傳的兩個值。 另外就是我又忘記泡沫排序ㄌ,直接抄我自己的東西= =
還有就是我malloc只allocate一個空間,怎麼就可以了,反而後面多allocate會出錯= =
是我哪裡不懂ㄇ?
總之,這題讚。

創(chuàng)作回應(yīng)

貓狗喵
你這種用法會破壞記憶體結(jié)構(gòu),影響其他東西的運作,但不一定會讓程式掛掉
2023-02-23 14:12:04
貓狗喵
你應(yīng)該記錄你的 array size 然後大小不足就 realloc
2023-02-23 14:12:28
テリ君(桃夫模式)
a = realloc(a, (i + 1) * sizeof(float)); 我加這行應(yīng)該就OKㄌ
2023-02-23 16:00:48
テリ君(桃夫模式)
感謝哥
2023-02-23 16:00:55

更多創(chuàng)作