我正在其中一个脚本中做一些附加操作,下面是一些简化的代码:
foreach($entry in $arr){
...
switch($entry.AccessRights)
{
"GenericRead" {$score = 1}
"GenericWrite" {$score = 2}
"GenericAll" {$score = 3}
default {$score = 0.1}
}
$users | where {$_.username -eq $entry.username} | % {$_.aclscore+=$score}
}
您期望输出为123.5之类的值。但是在两者之间的某个时间点(分数为0.1时),它会偏离0.0000000000001正负,所以我可能会得到类似66,1000000000001甚至84,8999999999999的结果。
问题1:为什么?
问题2:除了事后取整外,我还能做些什么来解决?
最佳答案
在测试时,PowerShell隐式将变量的数据类型强制转换为[double]
。而是显式转换为[decimal]
这绝不是深入的比较。我建议您阅读this table of datatypes并在线查找更完整的解释,因为这是非常基础的并且与语言无关。
代码
foreach($entry in $arr){
...
switch($entry.AccessRights)
{
"GenericRead" {[decimal]$score = 1}
"GenericWrite" {[decimal]$score = 2}
"GenericAll" {[decimal]$score = 3}
default {[decimal]$score = 0.1}
}
$users | where {$_.username -eq $entry.username} | % {$_.aclscore+=$score}
}
编辑-进一步的说明
由于数字存储在binary中,并且某些数字无法精确地用二进制表示,因此double数据类型缺乏精度。
沃尔特·米蒂(Walter Mitty)的评论提供了一个
1/3
的很好的例子,这个数字无法使用有限数量的十进制或二进制数字精确表示:1/3 = 0.333333333..... [decimal]
1/3 = 0.010101010..... [binary]
同样,分数
1/10
cannot be expressed exactly in binary。而可以十进制表示。1/10 = 0.1 [decimal]
1/10 = 0.000110011.... [binary]
关于powershell - Powershell添加不需要的小数(加法),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45674415/