Programming Fundamentals/Conditions/PowerShell
conditions.ps1
edit# This program asks the user for a Fahrenheit temperature,
# converts the given temperature to Celsius,
# and displays the results.
#
# References:
# https://www.mathsisfun.com/temperature-conversion.html
# https://en.wikiversity.org/wiki/PowerShell/Conditions
function Get-Choice()
{
Write-Host "Enter C to convert to Celsius or F to convert to Fahrenheit:"
$choice = Read-Host
return $choice
}
function Get-Temperature($label)
{
Write-Host "Enter $label temperature:"
$temperature = Read-Host
return $temperature
}
function Calculate-Celsius($fahrenheit)
{
$celsius = ([double]$fahrenheit - 32) * 5 / 9
return $celsius
}
function Calculate-Fahrenheit($celsius)
{
$fahrenheit = [double]$celsius * 9 / 5 + 32
return $fahrenheit
}
function Display-Result($temperature, $from, $result, $to)
{
Write-Host $($temperature + '° ' + $from + ' is ' + $result + '° ' + $to)
}
function Main()
{
# Main could either be an if-else structure or a switch-case structure
$choice = Get-Choice
# If-Else approach
if($choice -eq 'C' -or $choice -eq 'c')
{
$temperature = Get-Temperature "Fahrenheit"
$result = Calculate-Celsius $temperature
Display-Result $temperature "Fahrenheit" $result "Celsius"
}
elseif($choice -eq 'F' -or $choice -eq 'f')
{
$temperature = Get-Temperature "Celsius"
$result = Calculate-Fahrenheit $temperature
Display-Result $temperature "Celsius" $result "Fahrenheit"
}
else
{
Write-Host 'You must enter C to convert to Celsius or F to convert to Fahrenheit.'
}
# Switch-Case approach
switch ($choice)
{
C
{
$temperature = Get-Temperature "Fahrenheit"
$result = Calculate-Celsius $temperature
Display-Result $temperature "Fahrenheit" $result "Celsius"
}
F
{
$temperature = Get-Temperature "Celsius"
$result = Calculate-Fahrenheit $temperature
Display-Result $temperature "Celsius" $result "Fahrenheit"
}
default { Write-Host 'You must enter C to convert to Celsius or F to convert to Fahrenheit.' }
}
}
Main
Try It
editCopy and paste the code above into one of the following free online development environments or use your own PowerShell compiler / interpreter / IDE.
Online
edit- There are some options, but none are fully functional at this time.