1

我的 VB.NET 程序给了我两个错误:

  1. 当我输入负值或 0 时它不会中断。
  2. 它没有显示总值。

谁能帮我解决这个问题?

Enter deposit amount: 300
Another (y or n)? y
Enter deposit amount: -1
Amount cannot be zero or negative.

我的代码:

 Module Module1

 Sub Main()
    Dim userResponse As Char
    Dim depositAmount As Decimal
    Dim totalDeposits As Decimal

    Dim depositCount As Integer
    Dim averageDeposit As Decimal
    depositCount = 0
    totalDeposits = 0

    While Not (userResponse = "n")
        Console.WriteLine("Enter Desposit Amount:")
        If (depositAmount < 0 And depositAmount = 0) Then
            Console.WriteLine("Amount cannot be zero or negative.")
        Else
            depositAmount = Console.ReadLine()



            Console.WriteLine("Another (y or n)?")
            userResponse = Console.ReadLine()



            totalDeposits = totalDeposits + depositAmount
            depositCount = depositCount + 1
            averageDeposit = totalDeposits / depositCount

        End If
    End While


    Console.WriteLine("  Total deposits:               " + totalDeposits.ToString)
    Console.WriteLine("  Number of deposits:           " + depositCount.ToString)
    Console.WriteLine("Average deposit:     " + averageDeposit.ToString)

End Sub

End Module
4

2 回答 2

1

您也许可以尝试: If (depositAmount < 0 or depositAmount = 0) 据我所知,该值不能同时为负数和零。

于 2013-07-11T19:55:44.643 回答
0

当我输入负值或 0 时它不会中断。它不会显示总值。

您在没有打开选项的情况下进行编码并尝试将字符串隐式转换为十进制。此外,您在用户输入之前检查 depositamount。

尝试这样的事情:

 Module Module1

 Sub Main()
    Dim userResponse As Char
    Dim depositAmount As Double
    Dim totalDeposits As Double

    Dim depositCount As Integer
    Dim averageDeposit As Double
    depositCount = 0
    totalDeposits = 0
While Not (userResponse = "n")
    Console.WriteLine("Enter Desposit Amount:")
    'Attempt to convert readline to double. if it's successful GoodResponse
    'is true and depositamount has the value entered, otherwise it's 0
    Dim GoodResponse As Boolean = Double.TryParse(Console.Readline(), depositAmount)
    If Not GoodResponse OrElse depositAmount <=0 Then
        depositAmount = 0
        Console.WriteLine("Amount must be a number and cannot be zero or negative.")
    End If

        Console.WriteLine("Another (y or n)?")
        userResponse = Console.ReadLine()



        totalDeposits = totalDeposits + depositAmount
        depositCount = depositCount + 1
        averageDeposit = totalDeposits / depositCount

    End If
End While
于 2013-07-11T19:56:10.260 回答