【问题标题】:Why does min value return as zero and max return as a proper value为什么最小值返回为零而最大值返回为正确值
【发布时间】:2019-06-19 17:16:47
【问题描述】:
Dim Temp(3), Difference As Double
Dim i As Integer
Const UpperBound As Double = 37.5
Const LowerBound As Double = 36
For i = 1 To 3
    Console.WriteLine("Enter the temeperature of the baby.")
    Temp(i) = Console.ReadLine()
    If Temp(i) > UpperBound Or Temp(i) < LowerBound Then
        Console.WriteLine("The temperature is not in the correct range.")
    Else Console.WriteLine("The temperature is within acceptable range.")
    End If
Next
Console.WriteLine("The minimum temperature is " & Temp.Min)
Console.WriteLine("The maximum temperature is " & Temp.Max)
Difference = Temp.Max - Temp.Min
Console.WriteLine("The difference is " & Difference)

Console.ReadKey()

我得到的不是最小值,而是 0

【问题讨论】:

  • 欢迎来到 SO。今后,请花时间正确格式化您的代码。

标签: arrays vb.net max min


【解决方案1】:

数组是零索引的,并使用最高可寻址索引声明,所以当你

Dim Temp(3) 

您正在创建一个包含 4 个插槽 [0, 1, 2, 3] 的数组。 IMO 这是一个非常值得怀疑的语言设计。

在创建数组时,所有槽都初始化为值0。然后将值放入索引[1, 2, 3],而不是索引0

因此,数组将始终在索引 00 处具有值。

您可以通过首先声明 Temp 3 个插槽而不是 4 个来解决此问题:

Dim Temp(2)

然后调整你的循环:

For i = 0 To 2

https://docs.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/arrays/

【讨论】:

    【解决方案2】:

    为了将来参考,您可以使用GetLowerBound()GetUpperBound() 获取数组的下限和上限。这将允许您的代码工作,即使您稍后更改数组的大小(而不是在循环中硬编码上限):

    For i As Integer = Temp.GetLowerBound(0) To Temp.GetUpperBound(0)
        Debug.Print(i & ": " & Temp(i))
    Next
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-07
      • 2021-11-29
      • 2014-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-15
      • 2021-07-01
      相关资源
      最近更新 更多