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