函数中的除法(“/”)
我正在尝试编写一个简单的除法函数,但出现错误
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
我的错误是什么?谢谢
I'm trying to write a simple function of the division, but I get an error
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
What is my mistake? Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您错误地调用了该函数。函数调用的 Powershell 语法为:
而 (1,1) 是 Object[]。
如果您想防止这样的使用错误,请将函数声明为:
[Parameter(Mandatory=$true)] 确保给出两个值。无论如何,除法总是在 Powershell 中进行双除法,即使给出了整数,因此强制类型 [double] 不会停止整数的使用,并且会确保输入类型是您所期望的。
You are invoking the function incorrectly. Powershell syntax for function invocation is:
Whereas (1,1) is an Object[].
If you want to prevent usage mistakes like this, declare the function as:
the [Parameter(Mandatory=$true)] ensures both values are given. And division always does double division in Powershell anyway, even if integers are given, so enforcing type [double] won't stop integer usage and will make sure the input type is what you expect.
您应该在函数体中将除法运算符的参数强制转换为整数,否则
它们将被视为字符串(即使它们看起来像整数),并且字符串不支持 / 运算符:
[int] $x / [int] $y
You should cast the arguments of the division operator to ints in your function body, otherwise
they will be treated as strings (even if they look like ints), and strings don't support the / operator:
[int] $x / [int] $y