Function 函数中的除法(“/”)

Function 函数中的除法(“/”),function,powershell,syntax-error,argument-passing,Function,Powershell,Syntax Error,Argument Passing,我试图写一个简单的除法函数,但我得到了一个错误 PS C:\Users\john> Function Div($x, $y) { $x / $y } PS C:\Users\john> Div (1, 1) Method invocation failed because [System.Object[]] doesn't contain a method named 'op_Division'. At line:1 char:28 + Function Div($x, $y) {

我试图写一个简单的除法函数,但我得到了一个错误

PS C:\Users\john> Function Div($x, $y) { $x / $y }
PS C:\Users\john> Div (1, 1)
Method invocation failed because [System.Object[]] doesn't contain a method named 'op_Division'.
At line:1 char:28
+ Function Div($x, $y) { $x / <<<<  $y }
    + CategoryInfo          : InvalidOperation: (op_Division:String) [], RuntimeException
    + FullyQualifiedErrorId : MethodNotFound
PS C:\Users\john>函数Div($x,$y){$x/$y}
PS C:\Users\john>Div(1,1)
方法调用失败,因为[System.Object[]]不包含名为“op_Division”的方法。
第1行字符:28

+函数Div($x,$y){$x/您错误地调用了函数。函数调用的Powershell语法为:

Div 1 1
鉴于(1,1)是一个对象[]

如果要防止出现这样的使用错误,请将函数声明为:

Function Div([Parameter(Mandatory=$true)][double]$x, [Parameter(Mandatory=$true)][double]$y) { $x / $y }

[Parameter(Mandatory=$true)]确保两个值都给定。而且除法在Powershell中始终执行双除法,即使给定了整数,因此强制执行类型[double]不会停止整数的使用,并将确保输入类型符合您的预期。

您应该将除法运算符的参数强制转换为函数体中的整数,否则 它们将被视为字符串(即使它们看起来像int),并且字符串不支持/运算符:

[int]$x/[int]$y
函数Div($x,$y){[int]$x/[int]$y}
产生错误
无法将类型为“System.Object[]”的“System.Object[]”值转换为类型为“System.Int32”
。我相信VoidStar给出了正确的答案。可能的重复