【问题标题】:Why isn't my VB if statement working?为什么我的 VB if 语句不起作用?
【发布时间】:2016-10-14 14:25:26
【问题描述】:

我正在为我的 Visual Basic 编程课程做我的第一个项目。 我试图让这个条件语句说明折扣率是 0.1 还是(10%),然后添加到获得折扣的客户数量(msngFrequentFlyers)并添加到跟踪给定总折扣的累加器(msngTotalDiscounts )。

我对这一切都很陌生-请帮忙!项目将于今晚到期。

这是我的代码:

Public Class frmTaxiConsole
'Modular Variable Declaration Section
'Declares msngDiscountRate and sets inital value to -1 for testing user input
Dim msngDiscountRate As Single = -1
'Declares all counter variables
Dim msngNumberOfRides As Single
Dim msngNumberOfFrequentFlyers As Single
'Declares all accumulator variables
Dim msngRevenue As Single
Dim msngTotalDiscounts As Single
Dim msngBillableMiles As Single

如果勾选了折扣单选按钮:

    Private Sub radFrequentFlyer_CheckedChanged(sender As Object, e As EventArgs) Handles radFrequentFlyer.CheckedChanged
    msngDiscountRate = 0.1 'Sets discount rate to 10% upon selection of radio button
End Sub

这是在“处理事务”点击事件中不起作用的 if 语句:

        If msngDiscountRate = "0.1" Then 'Checks to see if this transaction had any discount
        msngNumberOfFrequentFlyers += 1 'If so, adds 1 to the number of discounts given
        msngTotalDiscounts = msngTotalDiscounts + (sngSubTotal * msngDiscountRate) 'Also adds the discount amount to the total discounts accumulator (without making it negative)
    End If

这是“处理事务”点击事件的完整代码:

 Private Sub btnProcessTx_Click(sender As Object, e As EventArgs) Handles btnProcessTx.Click
    'Local Variable Declaration Section
    Dim sngMilesDriven As Single
    Dim dblOdometerStart As Double
    Dim dblOdometerEnd As Double
    Dim sngInitialFee As Single
    Dim sngPerMileFee As Single
    Dim sngMileageCharge As Single
    Dim sngSubTotal As Single
    Dim sngDiscount As Single
    Dim sngTotalDue As Single

    'Data Input + Testing Section
    'Changes all text box backcolors white, in case they had been turned red due to an error
    txtOdometerStart.BackColor = Color.White
    txtOdometerEnd.BackColor = Color.White
    txtInitialFee.BackColor = Color.White
    txtPerMileFee.BackColor = Color.White
    'Try/Catch validates user input for Inital Fee 
    Try
        'Attempts to convert user input to Single and store as a local variable
        sngInitialFee = CSng(txtInitialFee.Text)
    Catch ex As Exception
        'If error occurs, displays a messagebox, changes background color of relavent text box, and exits sub.
        MessageBox.Show("Please enter a valid initial fee.", "Invalid Initial Fee", MessageBoxButtons.OK)
        txtInitialFee.BackColor = Color.Red
        txtInitialFee.Focus() 'Focuses in text box where error occured so user can fix
        Exit Sub
    End Try
    'Try/Catch validates user input for Per-Mile Fee
    Try
        'Attempts to convert user input to Single and store as a local variable
        sngPerMileFee = CSng(txtPerMileFee.Text)
    Catch ex As Exception
        'If error occurs, displays a messagebox, changes background color of relavent text box, and exits sub.
        MessageBox.Show("Please enter a valid per-mile fee.", "Invalid Per-Mile Fee", MessageBoxButtons.OK)
        txtPerMileFee.BackColor = Color.Red
        txtPerMileFee.Focus() 'Focuses in text box where error occured so user can fix
        Exit Sub
    End Try
    'Try/Catch validates user input for starting milage
    Try
        'Attempts to convert user input to Double and store as a local variable
        dblOdometerStart = CDbl(txtOdometerStart.Text)
    Catch ex As Exception
        'If error occurs, displays a messagebox, changes background color of relavent text box, and exits sub.
        MessageBox.Show("Please enter a valid starting milage.", "Invalid Odometer Reading", MessageBoxButtons.OK)
        txtOdometerStart.BackColor = Color.Red
        txtOdometerStart.Focus() 'Focuses in text box where error occured so user can fix
        Exit Sub
    End Try
    'Try/Catch validates user input for ending milage
    Try
        'Attempts to convert user input to Double and store as a local variable
        dblOdometerEnd = CDbl(txtOdometerEnd.Text)
    Catch ex As Exception
        'If error occurs, displays a messagebox, changes background color of relavent text box, and exits sub.
        MessageBox.Show("Please enter a valid ending milage.", "Invalid Odometer Reading", MessageBoxButtons.OK)
        txtOdometerEnd.BackColor = Color.Red
        txtOdometerEnd.Focus() 'Focuses in text box where error occured so user can fix
        Exit Sub
    End Try
    'If statement ensures Inital Fee is a positive number
    If sngInitialFee < 0 Then
        'If error occurs, displays a messagebox, changes background color of relavent text box, and exits sub.
        MessageBox.Show("Initial Fee cannot be negative.", "Invalid Inital Fee", MessageBoxButtons.OK)
        txtInitialFee.BackColor = Color.Red
        txtInitialFee.Focus() 'Focuses in text box where error occured so user can fix
        Exit Sub
    End If
    'If statement ensures Per-Mile Fee is a positive number
    If sngPerMileFee < 0 Then
        'If error occurs, displays a messagebox, changes background color of relavent text box, and exits sub.
        MessageBox.Show("Per-Mile Fee cannot be negative.", "Invalid Per-Mile Fee", MessageBoxButtons.OK)
        txtPerMileFee.BackColor = Color.Red
        txtPerMileFee.Focus() 'Focuses in text box where error occured so user can fix
        Exit Sub
    End If
    'If statement checks to make sure starting milage is smaller number than ending milage
    If dblOdometerEnd <= dblOdometerStart Then
        'If ending milage is smaller number than starting milage, displays a messagebox and exits sub.
        MessageBox.Show("Your ending mileage cannot be less than or equal to your starting mileage. Please check your odometer readings.", "Invalid Odometer Reading", MessageBoxButtons.OK)
        txtOdometerStart.Focus() 'Focuses in starting odometer reading text box so user can fix
        Exit Sub
    End If
    'If statement checks to make sure both odometer readings are positive numbers.
    If dblOdometerEnd < 0 Or dblOdometerStart < 0 Then
        'If either odometer reading is negative, displays a messagebox and exits sub.
        MessageBox.Show("Both your odometer readings must be positive numbers. Please check your odometer readings.", "Invalid Odometer Reading", MessageBoxButtons.OK)
        txtOdometerStart.Focus() 'Focuses in starting odometer reading text so user can fix
        Exit Sub
    End If
    'If statement checks to ensure user has seleted one of the two radio buttons
    If msngDiscountRate = -1 Then
        'If msngDiscountRate is the same as the initial value, neither option has been chosen, an error message is shown, and sub exited.
        MessageBox.Show("Please choose a frequent flyer status.", "Frequent Flyer?", MessageBoxButtons.OK)
        Exit Sub
    End If
    'Calculations Section
    sngMilesDriven = CSng(dblOdometerEnd - dblOdometerStart) 'Subtracts starting mileage from ending mileage, converts to single, stores as var sngMilesDriven
    sngMileageCharge = sngMilesDriven * sngPerMileFee 'Multiplies the miles driven by the per-mile fee and stores as var sngMileageCharge
    sngSubTotal = sngMileageCharge + sngInitialFee 'Adds the milage charge to the initial fee, stores as var sngSubTotal
    sngDiscount = sngSubTotal * msngDiscountRate * -1 'Multiplies subtotal by discount rate, makes negative, stores as var sngDiscount
    sngTotalDue = sngSubTotal + sngDiscount 'Subtracts discounts from subtotal, stores as var sngTotalDue
    'Counter and Accumulator Operations
    msngNumberOfRides += 1 'Adds 1 to the number of rides given
    If msngDiscountRate = "0.1" Then 'Checks to see if this transaction had any discount
        MsgBox(msngDiscountRate)
        msngNumberOfFrequentFlyers += 1 'If so, adds 1 to the number of discounts given
        msngTotalDiscounts = msngTotalDiscounts + (sngSubTotal * msngDiscountRate) 'Also adds the discount amount to the total discounts accumulator (without making it negative)
    End If
    msngRevenue = msngRevenue + sngTotalDue 'Adds the total due for current transaction to revenue accumulator
    msngBillableMiles = msngBillableMiles + sngMilesDriven 'Adds miles from this transaction to running total

    'Output Section
    'Displays above calculations in respective labels and formats as currency if neccecary.
    lblMilesDrivenOutput.Text = sngMilesDriven
    lblSumInitialFeeOutput.Text = FormatCurrency(sngInitialFee) 'Formats sngInitialFee as currency and displays in lblSumInitialFeeOutput
    lblSumMilageChargeOutput.Text = FormatCurrency(sngMileageCharge)
    lblSumSubTotalOutput.Text = FormatCurrency(sngSubTotal)
    lblSumDiscountOutput.Text = FormatCurrency(sngDiscount)
    lblSumTotalDueOutput.Text = FormatCurrency(sngTotalDue)
    'Displays all counter and accumulator variables after they are updated
    lblTotalRidesOutput.Text = msngNumberOfRides
    lblFrequentFlyersOutput.Text = msngNumberOfFrequentFlyers
    lblRevenueOutput.Text = FormatCurrency(msngRevenue)
    lblTotalDiscountsOutput.Text = FormatCurrency(msngTotalDiscounts)
    lblBillableMilesOutput.Text = msngBillableMiles


End Sub

【问题讨论】:

  • 开启 Option Strict。 If msngDiscountRate = "0.1" 正在将单个字符串与字符串进行比较
  • ^ 并研究选项/警告的最佳实践。这将为您节省大量时间和麻烦。
  • @plutonix 会 msngDiscountRate = csng(0.1) 修复它吗?感谢您的帮助
  • msngDiscountRate = 0.1 可以。 CSng(0.1) 不会做任何事情,因为 0.1 已经是 Single
  • 实际上,.01 将是 Double - VB 中的默认数据类型。 0.1F 将是 Single,但 VB 将允许 If msngDiscountRate = 0.1。您可能还有其他问题,在您打开 Option Strict 后设置断点并查看值是什么 - 因为其他地方的全局变量代码可能会更改它

标签: vb.net visual-studio conditional counter accumulator


【解决方案1】:

首先如上所述,您需要在 if 语句中删除 0.1 周围的引号,这将不起作用,因为它将数字与字符串进行比较。

我不是浮点运算方面的专家,但正如 Plutonix 所暗示的那样,我认为当您尝试不带引号时的问题是 0.1 您在 if 语句中比较您的 msngDiscountRate 默认为Double,而您已将变量声明为 Single,因此 if 语句的计算结果为 false。

您可以将msngDiscountRate 变量声明为Double,或者将0.1 转换为Single 以绕过它。这些简单的例子可能会有所帮助 -

    'Variable declared as a Single, compared to 0.1 (a Double) - If statement evaluates to false
    Dim msngDiscountRateExample1 As Single = -1
    msngDiscountRateExample1 = 0.1

    If msngDiscountRateExample1 = 0.1 Then
        Debug.Print(msngDiscountRateExample1.ToString)
    End If

    'Variable declared as a Double, compared to 0.1 (another Double) - If statement evaluates to true
    Dim msngDiscountRateExample2 As Double = -1
    msngDiscountRateExample2 = 0.1

    If msngDiscountRateExample2 = 0.1 Then
        Debug.Print(msngDiscountRateExample2.ToString)
    End If

    'Variable declared as a Single, compared to 0.1 (a Double) which is *cast* as a Single - If statement evaluates to true
    Dim msngDiscountRateExample3 As Single = -1
    msngDiscountRateExample3 = 0.1

    If msngDiscountRateExample3 = CSng(0.1) Then
        Debug.Print(msngDiscountRateExample3.ToString)
    End If

【讨论】:

    猜你喜欢
    • 2012-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-17
    • 2016-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多