Почему мой оператор VB if не работает?

Я работаю над своим первым проектом для своего класса визуального базового программирования. Я пытаюсь, чтобы в этом утверждении условия говорилось, что ставка скидки равна 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

person Sam Lev    schedule 14.10.2016    source источник
comment
Включите Option Strict. If msngDiscountRate = "0.1" сравнивает одиночное число со строкой   -  person Ňɏssa Pøngjǣrdenlarp    schedule 14.10.2016
comment
^ и изучите лучшие практики для опций/предупреждений. Это сэкономит вам много времени и головной боли.   -  person rory.ap    schedule 14.10.2016
comment
@plutonix исправит это с помощью msngDiscountRate = csng(0.1)? Спасибо за вашу помощь   -  person Sam Lev    schedule 14.10.2016
comment
msngDiscountRate = 0.1 будет работать. CSng(0.1) ничего не сделает, так как 0.1 уже Single.   -  person topshot    schedule 14.10.2016
comment
@Topshot У меня было так изначально, это не сработало. Затем я попробовал с кавычками и попробовал со скобками   -  person Sam Lev    schedule 14.10.2016
comment
На самом деле .01 будет Double — типом данных по умолчанию в VB. 0.1F будет Single, но VB позволит If msngDiscountRate = 0.1. У вас могут возникнуть другие проблемы, после того как вы включите Option Strict, установите точку останова и посмотрите, каковы значения, поскольку глобальный код переменной в другом месте может изменить ее.   -  person Ňɏssa Pøngjǣrdenlarp    schedule 14.10.2016


Ответы (1)


Во-первых, как упоминалось выше, вам нужно удалить кавычки вокруг 0.1 в вашем операторе if, это не сработает, поскольку оно сравнивает число со строкой.

Я не эксперт по арифметике с плавающей запятой, но, как намекает Plutonix, я думаю, что проблема, когда вы пробовали это без кавычек, заключается в том, что 0.1 вы сравниваете msngDiscountRate в операторе if по умолчанию с 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
person Parrybird    schedule 14.10.2016