Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell Math Problem?

function other3($x, $y)
{
    $tmp = $x + $y
    return $tmp
}

$x = 5
$y = 10

$a = other3($x, $y)
Write-Host $a

Keeps returning 5 10 when it should be returning 15, what's the deal?

like image 770
nullcakes Avatar asked Mar 21 '26 16:03

nullcakes


2 Answers

To call other3 with two parameters, drop the parenthesis "()" e.g.

$a = other3 $x  $y

The way you're currently calling it, actually passes one parameter, an array with two elements, i.e. 5 and 10. The second parameter is empty (probably defaults to null), meaning the addition does nothing and you simply return the $x parameter.

like image 56
cristobalito Avatar answered Mar 23 '26 07:03

cristobalito


You're passing a list (5,10) to the parameter $x and $null to $y.

When the function adds $null to the list, you just get the list back.

Adding some write-host statements to the function should make this clear:

function other3($x, $y)
{
    $tmp = $x + $y
    write-host "`x=($x)"
    write-host "`y=($y)"
    return $tmp
}

$x = 5
$y = 10

$a = other3($x, $y)
Write-Host $a
like image 39
Mike Shepard Avatar answered Mar 23 '26 07:03

Mike Shepard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!