Temperature conversions

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

```function convert-temperature{
param(
[double]\$temperature,

[parameter(Mandatory=\$true)]
[string]
[ValidateSet("C", "F", "K")]
\$inputTemp,

[parameter(Mandatory=\$true)]
[string]
[ValidateSet("C", "F", "K")]
\$outputTemp
)

Write-Verbose "Convert to Centigrade"
switch(\$inputTemp){
"C" {\$data = \$temperature}
"F" {\$data = (\$temperature -32) * (5/9 )}
"K" {\$data = \$temperature - 273.15}
}

switch(\$outputTemp){
"C" {\$output = \$data}
"F" {\$output = (\$data * (9/5)) + 32 }
"K" {\$output = \$data + 273.15}
}
[math]::round(\$output,2)
}```

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

Published Mon, Aug 8 2011 21:08 by RichardSiddaway
Filed under:

Leave a Comment

(required)
(required)
(optional)
(required)

Enter the numbers above: