无效值未破坏,结果未显示

时间:2013-07-11 19:41:59

标签: vb.net while-loop

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

  1. 输入负值或0时不会中断。
  2. 它没有显示总值。
  3. 任何人都可以帮我解决这个问题吗?

    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
    

2 个答案:

答案 0 :(得分:1)

您可以尝试:If(depositAmount&lt; 0或depositAmount = 0)从我看到的值不能同时为负和零。

答案 1 :(得分:0)

  

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

您在没有打开选项的情况下进行编码,并尝试将字符串隐式转换为Decimal。您也可以在用户输入之前检查存款金额。

尝试这样的事情:

 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