0

我的老师给我发了一封电子邮件,告诉我我的作业是写一段关于租车的代码:

Sub Main()
    Dim age, credit As Integer
    Dim name As String

    Console.WriteLine("This programme determines whether you can rent a car.")
    Console.WriteLine("Please enter your name...")
    name = Console.ReadLine

    Console.WriteLine(name & " how old are you?")
    age = Console.ReadLine

    Console.WriteLine("How much does your credit card currently hold? (£)")
    credit = Console.ReadLine

    If age < 18 Then
        Console.WriteLine("Sorry, " & name & " you are not old enough to rent a car, please use the bicycle hire company!")
    End If

    If age >= 18 And credit >= 5000 Then
        Console.WriteLine(name & " you are able to rent a car!")
    End If

    If age >= 18 And credit < 5000 Then
        Console.WriteLine("Sorry, " & name & " You are currently not able to rent a car.")
    End If

End Sub

这就是我要求你不要这样做的方式,就好像它一直在破坏控制结构然后又重新进入一样。你能用Else Ifs吗?

他所说的“它不断打破控制结构,然后又重新进入”是什么意思。

这是使用 ElseIf 的正确代码吗:

  Sub Main()
    Dim age, credit As Integer
    Dim name As String

    Console.WriteLine("This programme determines whether you can rent a car.")
    Console.WriteLine("Please enter your name...")
    name = Console.ReadLine

    Console.WriteLine(name & " how old are you?")
    age = Console.ReadLine

    Console.WriteLine("How much does your credit card currently hold? (£)")
    credit = Console.ReadLine()
    If age >= 18 And credit >= 5000 Then
        Console.WriteLine(name & " you are able to rent a car!")
    ElseIf age >= 18 And credit < 5000 Then
        Console.WriteLine("Sorry, " & name & " you are currently not able to rent a car.")
    ElseIf age < 18 Then
        Console.WriteLine("Sorry, " & name & " you are not old enough to rent a car, please use the bicycle hire company!")
    End If
End Sub 
4

1 回答 1

1

不。虽然我不知道你的老师想教你什么(你真的应该问他,他是专业的教育工作者,并且得到报酬来做这项工作),我相信他的意思是:

If age < 18 Then
    Console.WriteLine("...")
ElseIf credit < 5000 Then
    Console.WriteLine("...")
Else 
    Console.WriteLine(name & " you are able to rent a car!")
End If

请注意此代码如何易于维护。更改年龄或信用额度只需要编辑一个报表。这大大降低了出错的几率,也更容易阅读。

于 2013-10-13T15:03:46.193 回答