【问题标题】:Input a set of numbers and output the Largest, smallest and average输入一组数字并输出最大、最小和平均值
【发布时间】:2017-10-18 19:25:16
【问题描述】:

我正在使用 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

【问题讨论】:

  • I'm using VBscript 那么你使用了错误的标签。 VB.NET 之于 VBScript 就像 Car 之于 Carpet。请阅读How to Ask 并采取tour
  • 我从未做过任何 vb 脚本,但求平均值就像将所有元素相加并除以数组的计数一样简单。

标签: loops for-loop if-statement vbscript


【解决方案1】:

使用 WScript.Arguments 而不是 InputBox 和一个函数来计算值。如:

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

【讨论】:

  • 感谢您花时间写这篇文章,但问题是我在 Vbscript 方面的知识,因为我们的老师教给我们的不仅仅是条件语句、函数和“For”循环,我需要编写仅使用他教给我们的代码,这意味着没有数组或 WScript.Arguments 。这甚至可能开始吗?
  • @Dan 最好继续这样做。
猜你喜欢
  • 1970-01-01
  • 2018-07-07
  • 2013-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多