summaryrefslogtreecommitdiff
path: root/reference/C/CONTRIB/SNIP/inchcvrt.c
blob: fb2cdb60bfffb5f9f340eb7f5011de450469554b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/*
**  Convert English measurement units
**
**  Takes command line arguments in inches and converts to:
**
**  1. feet and inches (expressed as floating point)
**  2. feet and inches (expressed as fraction)
**
**  public domain demo by Bob Stout
**  uses ROUND.H from SNIPPETS
*/

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "round.h"

#define BASE 64.0

void cnvrt_inches(double  input,
                  double *feet,
                  double *inches,
                  double *dec_inches,
                  double *num_inches,
                  double *den_inches)
{
      double quot, rem, temp;

      /*
      **  Split feet and inches
      */

      *feet   = floor(input / 12.0);
      *inches = fmod(input, 12.0);

      /*
      **  Get integer inches and fractions
      */

      *num_inches = modf(*inches, dec_inches) * BASE;

      *num_inches = fround(*num_inches, 0);
      if (0.0 == *num_inches)
            return;

      /*
      **  Reduce fractions to lowest common denominator
      */

      for (*den_inches = BASE;
            0.0 == fmod(*num_inches, 2.0);
            *den_inches /= 2.0, *num_inches /= 2.0)
      {
            ;
      }
}

main(int argc, char *argv[])
{
      double arg, feet, inches, dec, num, den, dummy;

      while (--argc)
      {
            arg = atof(*(++argv));
            cnvrt_inches(arg, &feet, &inches, &dec, &num, &den);
            printf("%f Inches = %d' %.5f\" or %d' %d",
                  arg, (int)feet, inches, (int)feet, (int)dec);
            if (0.0 == num)
                  puts("\"");
            else
            {
                  printf("-%d/%d\"", (int)num, (int)den);
                  if (modf(num, &dummy))
                        puts(" (approx.)");
                  else  puts("");
            }
      }
      return EXIT_SUCCESS;
}