如何在数组中添加数字总和 [英] How to add a sum of numbers in an array

查看:107
本文介绍了如何在数组中添加数字总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是学习Powershell的新手,希望最终能进一步提高我在其他程序中的经验.目前,在It和Powershell类中学习课程已成为我的敌人.在我们必须制作的一个脚本中,我们需要创建一个脚本,该脚本将在单击按钮后添加在数组中输入的数字,在这种情况下,该按钮的值为'0'.我尝试了各种脚本,但是不断出错,对您的帮助将不胜枚举,并且请记住,我是新手,所以现在响应越简单越好,对我会有所帮助,如果可能的话,请解释为什么我的代码是错误的

I am new in learning powershell and hoping to further my experience in other programs eventually. Currently doing a course in It and in my powershell class lopps have become a bit of an enemy of mine. In one script that we have to make, we need to create a script that will add numbers inputted in an array after the click of a button, in this scenario that button with be '0'. I have attempted various scripts but keep getting errors any help would be much appreaciated and keep in mind that i am new so the simpler the response for now the best it will help me and if possible explain why my code is wrong

Do {

    $input = Read-Host 'Enter variety of numbers and press 0 to add them together'

    if ($input -eq '0') {
        $sum = [int]$sum + ',' + [int]$sum
        Write-Host 'Sum of numbers entered' $sum
    }

}
while ($input -ne '0')

推荐答案

变量$ input是保留的powershell变量(

The variable $input is a reservd powershell variable (take a look here) and you should not use it in this context.
As in the comments mentiond I would also put an else in your loop and save the input to an array.

[System.Int32[]]$UserInputs = @() #INT Array
do {

    [System.Int32]$UserInput = Read-Host -Prompt 'Enter variety of numbers and press 0 to add them together'

    if ($UserInput -eq 0)
    {
        Out-Host -InputObject ('Sum of numbers entered ' + ($UserInputs | Measure-Object -Sum).Sum) #Return the sum
    }
    else
    {
        $UserInputs += $UserInput #Add user input to array
    }
}
while ($UserInput -ne 0)

这篇关于如何在数组中添加数字总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆