【问题标题】:Random Number weirdness powershell question [duplicate]随机数怪异powershell问题[重复]
【发布时间】:2019-09-13 00:04:14
【问题描述】:

我编写了这两个函数来获得 1 到 10 X 次的随机数。

function randomNum(){
    $availableNums = 1..9
    $availableNums | Get-Random
}

function randNumXTimes($x){
    $global:rando = @()
    for($i; $i -lt $x; $i++){
        $rando += randomNum;
        $rando
    }
}

如果我执行randomNum 函数,它总是会做它应该做的事情,它会给我一个随机数 1 到 9。

然后我有这个函数randNumXTimes,如果我运行这个调用randomNum 函数的函数,它现在会产生随机的两位数,它们应该只是个位数。

什么鬼?

来自 randomNum 的示例结果:6 7 2 7 8 2

来自 randNumXTimes 的示例结果,它只是运行 randomNum 函数 X 次...

(randNumXTimes 10):7 12 20 25 30 36 43 45 51 53

我的问题是,当它看起来应该只产生个位数 X 次时,为什么这样做呢?我该如何解决这个问题?

【问题讨论】:

  • 您将$rando 定义为global 数组,然后将项目添加到$rando **_而不涉及全局范围。如果您在 $rando 行之后添加 $rando.GetType(),您会看到它不是一个数组 - 它是一个 int。

标签: powershell


【解决方案1】:

虽然您在函数开始时为 $global:rando 分配了一个空数组,但您实际上从未使用过它 - 请参阅内联 cmets:

function randNumXTimes($x){
    # create global var "rando"
    $global:rando = @()
    for($i; $i -lt $x; $i++){
        # assign to local var "rando" - not the same as $global:rando
        # its type will be [int], which is why the numbers keep adding up
        $rando += randomNum;
        $rando
    }
}

解决方法很简单,就是不要依赖全局变量:

function randNumXTimes($x) {
    for($i = 0; $i -lt $x; $i++){
        randomNum
    }
}

您可以通过一个函数轻松完成这两件事:

function Get-RandomDigit {
    param(
        [Parameter(Position = 0)]
        [ValidateRange(1,2147483647)]
        [int]$Count
    )

    for($i = 0; $i -lt $Count; $i++){
        1..9 |Get-Random
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-21
    • 2014-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多