vb.net - 此代码是否是此任务的正确代码?
问题描述
创建一个名为 swapped 的函数,它将接受两个名为 byref 的整数 (a,b) 并返回一个布尔值,如果数字已被交换,则返回 true。在例程中比较数字,如果 b>a 使用局部变量 temp 交换它们,则返回值 true,否则返回值 false。
Function swapped(ByRef a As Boolean, ByRef b As Boolean)
a = True
b = True
If b > a Then
temp = b
b = a
a = temp
a = True
b = True
Else
a = False
b = False
End If
解决方案
首先让我们看看你的代码。
'The requirements called for 2 Integers, not Booleans.
'A Function requires a datatype, in this can a Boolean
Private Function swapped(ByRef a As Boolean, ByRef b As Boolean)
'Assigning values here will overwrite the passed in values
a = True
b = True
'What would it mean for True > True ??
If b > a Then
'temp isn't declared so this will not compile
temp = b
'here I think you are trying to do the swap
'but all the values are True
b = a
a = temp
a = True
b = True
Else
a = False
b = False
End If
'Function need a return value to match the datatype of the function
'It is preceded by Return
End Function
如果您在 Visual Studio(免费下载)中工作,则会为您突出显示其中的几个错误。
现在,让我们看一些可以完成任务的代码。
'Through comments you have already figured out that a and b are Integers
'In addition, Functions always need a return type. In this case a Boolean
Function swapped(ByRef a As Integer, ByRef b As Integer) As Boolean
'The values of a and b are passed to the function.
'Keep the passed in value of a in a new variable
If b > a Then
Dim aPassedInValue = a
'assign the value of b to a
a = b
'now assign the original value of a to b
'we can't use a because we just changed the value of a in the above line
b = aPassedInValue
'There have been no errors so we can return True
Return True
Else 'We didn't swap them
Return False
End If
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim c As Integer = 7
Dim d As Integer = 20
MessageBox.Show($"c = {c}, d = {d}", "Before Swap")
Dim ReturnValue = swapped(c, d)
MessageBox.Show($"The return value of the swapped Function is {ReturnValue}")
MessageBox.Show($"c = {c}, d = {d}", "After Swap")
End Sub
我认为这个练习的重点是演示 ByRef。您已更改函数中的值,新值反映在 Button.Click Sub 的变量中。
推荐阅读
- cassandra - 如何在 cassandra 3.11.9+ dynamic_snitch_badness_threshold cassandra.yaml 参数上禁用 dynamic_snitch
- node.js - 无法在电子锻造应用程序中使用本机节点模块
- node.js - gcloud app部署服务自动重启
- mysql - 在我的 mysql 代码中出现错误:您的 SQL 语法有错误
- python - 安装 ta-lib 失败
- python - NLTK:同现矩阵
- sql - GroupBy(MS SQL Server 与 MySQL)
- android - 重置/清除视图模型或实时数据
- spring-webflux - 使用 WebFlux 执行两次环绕注释
- c++ - 如何使用while循环c ++计算输入值?