Advertisement
cd62131

Sort by BMI

Jan 15th, 2014
751
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.05 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. typedef struct {
  4.   char name[64];
  5.   double height;
  6.   double weight;
  7. } person;
  8.  
  9. double bmi(person p) {
  10.   double a = p.height / 100;
  11.   return p.weight / (a * a);
  12. }
  13.  
  14. void swap(person *p1, person *p2) {
  15.   person p = *p1;
  16.   *p1 = *p2;
  17.   *p2 = p;
  18. }
  19.  
  20. void sort_by_bmi(person *p, int n) {
  21.   int k = n;
  22.   while (k >= 0) {
  23.     int j = -1;
  24.     for (int i = 1; i <= k; i++) {
  25.       if (bmi(p[i - 1]) > bmi(p[i])) {
  26.         j = i - 1;
  27.         swap(&p[j], &p[i]);
  28.       }
  29.     }
  30.     k = j;
  31.   }
  32. }
  33.  
  34. int main(void) {
  35.   person p[] = {
  36.     { "一郎", 180.3, 77.1 },
  37.     { "二郎", 188.0, 93.0 },
  38.     { "三郎", 170.0, 63.0 },
  39.     { "四郎", 171.8, 59.0 },
  40.     { "五郎", 168.1, 56.5 },
  41.     { "六郎", 173.7, 69.4 },
  42.     { "七郎", 178.5, 60.3 },
  43.     { "八郎", 175.2, 70.9 },
  44.     { "九郎", 169.6, 55.7 },
  45.   };
  46.   sort_by_bmi(p, sizeof(p) / sizeof(person));
  47.   for (int i = 0; i < sizeof(p) / sizeof(person); i++) {
  48.     printf("%i: %s (%.1f)\n", i, p[i].name, bmi(p[i]));
  49.   }
  50.   return EXIT_SUCCESS;
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement