【问题标题】:VB console app - Why does array.Min() method return a value of 0 in the sorted array when 0 was not enteredVB 控制台应用程序 - 为什么 array.Min() 方法在未输入 0 时在排序数组中返回值 0
【发布时间】:2021-09-08 00:09:57
【问题描述】:

它是一个非常简单的程序,用于向 GCSE 学生展示如何使用 min()、max() 等数组函数,但是当通过 For 循环输入数据时结果不正确 - 当数据属于数组编码。

Dim testscores(10) As Integer
    'Dim testscores = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}  'min function works on this but not when values are entered using the FOR loop
    Dim studentname As String
    For x = 0 To 9
        Console.WriteLine("this is the x value " & x)
        Console.WriteLine("please enter a test score")
        testscores(x) = Console.ReadLine()
    Next
    Console.WriteLine()
    For y = 0 To 9
        Console.WriteLine("element y is " & y & "  " & " the value stored is " & testscores(y))
    Next
    Array.Sort(testscores)
    Console.WriteLine()
    For y = 0 To 9
        Console.WriteLine("after sorting - element y is " & y & "  " & " the value stored is " & testscores(y))
    Next`

输出如下所示: output when entering sequence of numbers

【问题讨论】:

  • 你在这里声明了多少个元素:Dim testscores(10) As Integer? -- 设置Option Strict ON
  • Dim testscores(10) 由于 Integer 创建了一个包含 11 个元素的数组,因此在输入值和打印输出时,您只需迭代前 10 个元素。 docs.microsoft.com/en-us/dotnet/visual-basic/programming-guide/…。或者将 for 循环的上限设置为 testcores.Length - 1
  • 整数是值类型。值类型具有默认值。 Integer 的默认值为零。数组的第 11 个元素使用 Integer 的默认值填充。

标签: arrays vb.net methods console


【解决方案1】:

正如 cmets 指出的那样,这一行:

Dim testscores(10) As Integer

导致创建这个 11 长的数组:

{0,0,0, 0,0,0, 0,0,0, 0,0}

然后,您使用循环为其中的 10 个项目赋值。假设您的用户每次输入 5:

{5,5,5, 5,5,5, 5,5,5, 5,0}

最后一个元素永远不会设置并保持其默认值 0,Min() 很乐意为您找到它..

如果你想使用 size 而不是 last index 来声明数组,我可以推荐 C# 吗? :)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-19
    • 2014-04-30
    • 1970-01-01
    • 2014-02-25
    • 1970-01-01
    • 2015-12-10
    • 1970-01-01
    相关资源
    最近更新 更多