Some Weighty Conversions

The three units of weight I’m familiar with are pounds, kilograms, and stone. For me, stone is the odd one. I’ve heard it used in Britain and it’s completely baffling to me, often requiring that I whip out a calculator to see what “14 stone” really means. Better, I could write code that converts between pounds, kilograms, and stone, which is the goal of this month’s Exercise.

For example, if I hear “14 stone” on a British TV show, I must do the math in my head: One stone is 14 pounds, so 14 stone is 14 × 14, which is (uses calculator) 196 pounds.

To make such a conversion in a computer program, you could input information like this:

14SP

This cryptic text reads, “Convert 14 stone into pounds.” The value 14 is the quantity, and the single-letter suffixes control the conversion: S for stone into P for pounds.

Or if you wanted to know how many kilograms are in 196 pounds, you type:

196PK

Which translates as, “Convert 196 pounds into kilograms.” The computer dutifully spits out the value 88.9 kilos.

Your task for this month’s Exercise is to write such a program.

The code prompts for input, as in this example:

Type a value to convert, suffixed by conversion types:
K - kilos, P - pounds, S - stones
Example: 2.0PK (convert 2.0 pounds to kilograms)
Convert:

The text input (standard input) is examined to pluck out a value from the string. Then the code examines the next two characters to determine the conversion. Invalid input is rejected.

The conversions required are:

Kilos to Pounds: 2.20462
Kilos to Stone: 0.127473
Pounds to Kilos: 0.453592
Pounds to Stone: 0.714286
Stone to Kilos: 6.35029
Stone to Pounds: 14.0

This Exercise began as a simple conversion table, but I decided to spice it up and have the code determine the conversion based upon input. This addition is the real challenge, not only to properly convert the string input into a value but to validate and interpret the two conversion characters.

Please try this Exercise on your own before you peek to see my solution.

Leave a Reply