Block of Code

Practical Examples for Programmers

  • Home
  • C++
  • Java
  • Visual Basic
  • Discrete Math
  • Ask a Question

Unit Price

Write a Visual Basic program that requests the price and weight of an item in pounds and ounces, and then determine the price per ounce. See the figure below for one possible outcome.

Unit Price

Suggested Control Names and Attributes:

Name Property Text Property ReadOnly Property Control Type Notes
frmUnitPrice Unit Price N/A Form Holds Controls
txtPrice  N/A N/A Text Box Captures the price of an item
txtPounds  N/A  N/A Text Box Captures the number of pounds an item weighs
txtOunces N/A N/A Text Box Captures the number of ounces an item weighs
btnDetermine Determine Unit Price N/A Button Triggers event for displaying price of an item per ounce
txtUnitPrice N/A True Text Box Displays the price of an item per ounce

Hints:

  • One pound is equal to 16 ounces.
  • To display the price per ounce with two decimal places, use the “ToString” function to convert from a string to currency.

Write the Code:

' Project: Unit Price
' Programmer: Your Name Here
' Date: February 3, 2014
' Description: Calculates the price per ounce of an item. User inputs
' the item price and weight in pounds and ounces. The price per ounce
' is calculated and displayed.

Public Class frmUnitPrice

   Private Sub btnDetermine_Click(sender As Object, e As EventArgs) Handles btnDetermine.Click
      ' Declare and initialize the variables
      Dim price As Double = 0
      Dim pounds As Integer = 0
      Dim ounces As Integer = 0
      Dim unitPrice As Double = 0
      Dim totalOunces As Integer = 0
      price = CDbl(txtPrice.Text)
      pounds = CInt(txtPounds.Text)
      ounces = CInt(txtOunces.Text)

      ' Calculate the price per ounce
      totalOunces = (pounds * 16) + ounces
      unitPrice = price / totalOunces

      ' Display the results
      txtUnitPrice.Text = unitPrice.ToString("C")
   End Sub
End Class

Secondary Sidebar

This is the secondary sidebar

Copyright © 2025 · Metro Pro Theme on Genesis Framework · WordPress · Log in