Robson » Little Red Book » Units conversion #1

Chapter 2 - Question 1

Write programs to convert imperial units to metric for each of the following pairs:

Input is to be a number representing a quantity in the imperial unit given by the program; output is to be equivilant amount and the metric unit involved.

Solution 1

I decided to use C++ for this solution so that I could learn more about that language. This is the first C++ application that I've written that does something useful, so the code is probably terrible!

The questions asks for "programs" but I've done it as one program so I could learn about arrays.

#include <stdio.h>
 
int main(int argc, char *argv[])
{
   bool bExit = false;
   char *cFrom[] =  { "inches",      "feet",   "miles",      "ounces",   "pounds"    };
   char *cTo[] =    { "centimetres", "metres", "kilometers", "grams",    "kilograms" };
   float fRatio[] = { 2.54,          0.3048,   1.609344,     28.3495231, 0.45359237  };
   int iType;
   float fAmount;
 
   while (!bExit)
   {
       for (int n = 0; n < 5; n++)
           printf(" %d. Convert %s to %s\n", n+1, cFrom[n], cTo[n]);
 
       printf("\nType a number from 1 to 5 or anything else to exit.\n>");
       scanf("%d", &iType);
       
       if (iType >= 1 && iType <= 5)
       {
           printf("\nHow many %s?\n>", cFrom[iType-1]);
           scanf("%f", &fAmount);
           printf("\n%g %s is %g %s.\n\n- - -\n\n", fAmount, cFrom[iType-1], fAmount * fRatio[iType-1], cTo[iType-1]);
       }  
       else
           bExit = true;
   }
   
   return 0;
}

Example output:

Example output from the conversion program

Log

© 2004-17 robson | cc unless stated