2016-10-14 4 views
0

Я работаю над своим первым проектом для своего основного базового класса программирования. Я пытаюсь сказать это условие, если ставка дисконтирования равна .1 или (10%), а затем добавьте к счету клиентов, получивших скидку (msngFrequentFlyers), и добавьте в аккумулятор, который отслеживает общие скидки (см. msngTotalDiscounts).Почему мой оператор VB не работает?

Я очень новичок во всем этом, пожалуйста, помогите! Проект должен состояться сегодня вечером.

Вот мой код:

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 

Это если утверждение, что не работает, в «Process Транзакции» нажмите событие:

 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 

Полный текст для события щелчка "Process Transaction":

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 
+2

Включить опцию Строгий. 'Если msngDiscountRate =" 0.1 "' сравнивает сингл с строкой – Plutonix

+0

^и изучает лучшие практики для опций/предупреждений. Это сэкономит вам много времени и головных болей. –

+0

@plutonix будет msngDiscountRate = csng (0.1) исправить? Спасибо за вашу помощь. –

ответ

0

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

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