I want to write a program which can converts one unit to another unit. Let's say I have 2 methods.First method can do metric conversions, second method can do weight conversitons. For example;
1. long km=metricConvLength(long mil,Enum.mil,Enum.km);//first method
2. long agirlik=metricConvWeight(long kg,Enum.mil,Enum.km);//second method
I want to use Enum struct for these variables. My program can convert these things and opposites;
My Question: I don't want to use if-else
or switch-case
structs for conversions.(Because if I use if-else struct,my code looks like so bad, much easy and slow.And I need more then 50 if-else struct when if I use these struct.This is grind.)
Can I write an algorithm for these conversions without using if-else or switch-case. My purpose is less code, more work. Any tips about algorithm?
To convert from one unit to another within the metric system usually means moving a decimal point. If you can remember what the prefixes mean, you can convert within the metric system relatively easily by simply multiplying or dividing the number by the value of the prefix.
Metric units of measurement differ by powers of 10 - 10, 100, 1,000, and so on. Thus, converting from one metric unit to another is always accomplished by multiplying or dividing your initial measurement by the appropriate power of ten.
You do not need an if-then-else
- in fact, you do not need control statements in your program. All you need is a lookup table - a Map
that translates your unit enum to a double
conversion factor, such that multiplying the measure in units by the conversion factor you get meters for units of space, and kilos for units of weight. Conversely, dividing meters by that factor gives you the desired units.
With this map in hand, you can do conversions for all pairs of units:
Cs
for the source unitsCd
for the destination unitsvalue * Cs / Cd
as your result.For example, let's say that you want to deal with meters, yards, inches, and feet. Your map would look like this:
Now let's say you want to convert 7.5
yards to feet:
Cs = 0.9144
Cd = 0.3048
Res = 7.5 * 0.9144 / 0.3048 = 22.5
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With