Monthly Archive

Temperature conversions

I was thinking about temperature conversions and decided to play around with the numbers

function convert-temperature{            
 [ValidateSet("C", "F", "K")]            
 [ValidateSet("C", "F", "K")]            
Write-Verbose "Convert to Centigrade"            
 "C" {$data = $temperature}            
 "F" {$data = ($temperature -32) * (5/9 )}            
 "K" {$data = $temperature - 273.15}            
 "C" {$output = $data}            
 "F" {$output = ($data * (9/5)) + 32 }            
 "K" {$output = $data + 273.15}            

So I wrote a little function.

The obvious conversions are fahrenheit to and from centigrade but I also wanted to include the kelvin scale.

This made the number of permutations quite high so I ended up with using two switch statements

The input temperature must be one of C, F or K as must the output

The first switch statement converts the incoming temperature to centigrade and the second converts it to the appropriate output temperature scale.

This is easier to understand and maintain than a series of if statements to determine whats come in and what needs to go out. Converting to an intermediate value may seem like an extra step but in this case it does simplify things

Leave a Reply