输入一组数字并输出最大,最小和平均值

时间:2017-10-18 19:25:17

标签: loops for-loop if-statement vbscript

我正在使用VBscript。

因为标题说我需要输入一组数字,我必须输出最大的数字,最小的和平均数。

我不知道如何做平均值,但是我做了最大和最小但却出现了错误(“堆栈空间不足”“最大”第6行)

(抱歉格式不确定如何编辑)

function Largest(a)
    maxi = -99999
    if a>maxi then
    maxi=a
end if
msgbox Largest(a)
end function

function Smallest(a)
    maxi = +99999
    if a<maxi then
    maxi=a
end if
msgbox Smallest(a)
end function



n = inputbox("Enter the numbers of items")
for i = 1 to n
a = CInt(InputBox("Enter Item " &i))
Largest(a)
Smallest(a)
next

我想了解如何计算平均值,但不知道如何将其合并到上面的代码中:

n=inputbox("Enter number of items")
sum = 0
for i = 1 to n
a = inputbox("enter items "&i)
sum = sum + a
next
avg = sum/n
msgbox avg

1 个答案:

答案 0 :(得分:2)

使用WScript.Arguments而不是InputBox,只使用一个Function来计算值。如:

Option Explicit

' returns average, minimum, and maximum of the non-empty 
' array a containing only numbers 
Function avmima(a)
  If "Variant()" <> TypeName(a) Then Err.Raise 4711, "needs array", "avmima"
  If -1 = UBound(a)             Then Err.Raise 4712, "needs non-empty array", "avmima" 
  If Not IsNumeric(a(0))        Then Err.Raise 4713, "needs array of numbers", "avmima" 
  Dim t : t = Array(a(0), a(0), a(0))
  Dim i
  For i = 1 To UBound(a)
      If Not IsNumeric(a(i)) Then Err.Raise 4714, "needs array of numbers", "avmima" 
      t(0) = t(0) + a(i)
      If t(1) > a(i) Then t(1) = a(i)
      If t(2) < a(i) Then t(2) = a(i)
  Next
  t(0) = t(0) / i 
  avmima = t 
End Function

Dim a : a = Array(1, 2, 3)
If 0 < WScript.Arguments.Unnamed.Length Then
   ReDim a(WScript.Arguments.Unnamed.Length - 1)
   Dim i    
   For i = 0 To UBound(a)
       a(i) = CDbl(WScript.Arguments.Unnamed(i))
   Next
End If 
WScript.Echo Join(a, vbTab) 
WScript.Echo Join(avmima(a), vbTab)
WScript.Echo Replace("Av Mi Ma", " ", vbTab)

'a = avmima("")
'a = avmima(Array())
'a = avmima(Split("1 Zwei 3"))

输出:

cscript avmima.vbs
1       2       3
2       1       3
Av      Mi      Ma

cscript avmima.vbs 0 0 0
0       0       0
0       0       0
Av      Mi      Ma

cscript avmima.vbs -1 -2 -3
-1      -2      -3
-2      -3      -1
Av      Mi      Ma

cscript avmima.vbs 1,5 2,5 5,0 (german locale!)
1,5     2,5     5
3       1,5     5
Av      Mi      Ma