谁能帮助我了解什么是错误的这段代码



这是一个非常愚蠢的练习

给定一个n个整数数组,从数组中移除第一个最大元素和最后一个最小元素。

谁能帮我弄明白是怎么回事?这是我第一次用VB写。

Imports System
Public Module Program
Public Sub Main(args() As string)
Dim numbers = New Integer() {1, 2, 4, 8, 5, 4, 9, 63, 2, 7, 0, 5, 4, 2}

Console.WriteLine("Initial Array {0}" + target)

Dim targetSize As Integer = numbers.Length - 2
Dim target(targetSize) As Integer

Dim max = numbers(0)
Dim maxIndex = 0

Dim min = numbers(0)
Dim minIndex = 0

For index = 0 To numbers.Length
If max < numbers(index) Then 
maxIndex = index
Stop
End If
Exit For

For index = 0 To numbers.Length
If min > numbers(index) Then 
minIndex = index
End If
Exit For

Dim targetIndex As Integer = 0

For index = 0 To numbers.Length
If (index <> minIndex Or index <> maxIndex) Then
target(targetIndex) = numbers(index)
targetIndex = targetIndex + 1
End If
Exit For
Console.WriteLine("Target Array {0}" + target)
End Sub
End Module

And This is the Output.

Visual Basic.Net Compiler version 0.0.0.5943 (Mono 4.0.1 - tarball)
Copyright (C) 2004-2010 Rolf Bjarne Kvinge. All rights reserved.
/runtime/vb/3yn8kpgq9_3ynmpk553/HelloWorld.vb (40,9) : error VBNC30084: CHANGEME
/runtime/vb/3yn8kpgq9_3ynmpk553/HelloWorld.vb (40,9) : error VBNC30084: CHANGEME
/runtime/vb/3yn8kpgq9_3ynmpk553/HelloWorld.vb (40,9) : error VBNC30084: CHANGEME
There were 3 errors and 0 warnings.
Compilation took 00:00:00.4196520
Error: Command failed: timeout 7 vbnc HelloWorld.vb

在线编辑器

您的代码有几个问题,例如:

  • target未被声明
  • for循环没有Next
  • Stop应该是Exit For
  • 逻辑被打破了,你想要最小值和最大值,但你不检查所有
  • 数组是固定大小的,你不能删除项目,使用List(Of T)

可以简化为:

Dim numbers As Int32() = {1, 2, 4, 8, 5, 4, 9, 63, 2, 7, 0, 5, 4, 2}
Dim min As Int32 = numbers.Min()
Dim max As Int32 = numbers.Max()
Dim numberList As List(Of Int32) = numbers.ToList()
Dim indexOfFirstMax As Int32 = numberList.IndexOf(max)
numberList.RemoveAt(indexOfFirstMax)
Dim indexOfLastMin As Int32 = numberList.LastIndexOf(min)
numberList.RemoveAt(indexOfLastMin)
numbers = numberList.ToArray()

最新更新