I startet with Powershell and tried to do a simple calculator.
This is what I have:
Function ReturnRes ($x,$y,$z)
{
$res= [float] $z [float]$y
return $res
}
Write-Host $res
$var1 = Read-Host "Zahl1"
$var2 = Read-Host "Zahl2"
$op = Read-Host "Operator(+-*/)"
ReturnRes -x $var1 -y $var2 -z $op
But I can't use the $z variable as an operation...
Any ideas?
You can use Invoke-Expression:
PS C:\> $x,$y,$op = '1.23','3.21','+'
PS C:\> Invoke-Expression "$x$op$y"
4.44
Make sure you validate the input:
Function Invoke-Arithmetic
{
param(
[float]$x,
[float]$y,
[ValidateSet('+','-','*','/')]
[string]$op
)
return Invoke-Expression "$x $op $y"
}
Here's another solution, add a default case to the switch to handle non-valid operators:
Function ReturnRes($x,$y,$z){
switch($z){
"+" {[float]$x + [float]$y}
"-" {[float]$x - [float]$y}
"*" {[float]$x * [float]$y}
"/" {[float]$x / [float]$y}
}
}
Write-Host $res
$var1 = Read-Host "Zahl1"
$var2 = Read-Host "Zahl2"
$op = Read-Host "Operator(+-*/)"
ReturnRes -x $var1 -y $var2 -z $op
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