Friday, January 28, 2011

Word Problems #1

This post is including word problems that are figured by using a program to solve them.

1. Morgan collects stuffed animals, and she has 6 cows and 7 sheep. How many stuffed animals does she have? Here's how I did it:
    
     Dim cows, sheep, total As Double
  
     cows = 6
  
     sheep = 7
  
     total = cows + sheep
  
       MessageBox.Show(total)   

2. Diane bought 7 mega burgers. Each mega burger cost $4. How many dollars did she spend on the mega burgers?
 Dim bAmount, bCost, total As Integer
  
     bAmount = 7
  
     bCost = 4
  
     total = bAmount * bCost
  
     MessageBox.Show("The cost of burgers is " & FormatCurrency(total))  

3. Ole has 15 apples and 12 oranges. How many pieces of fruit does he have?
 Dim apples, oranges, total As Double
  
 apples = 15
  
 oranges = 12
  
 total = apples + oranges
  
 MessageBox.Show("He has " & total & " pieces of fruit.")  

Wednesday, January 26, 2011

String Concatenation

The & Operator (Visual Basic) is defined only for String operands, and it always widens its operands to String, regardless of the setting of Option Strict. The & operator is recommended for string concatenation because it is defined exclusively for strings and reduces your chances of generating an unintended conversion.
 Dim a As String = "abc"
  
 Dim d As String = "def"
  
 Dim z As String = a & d
  
 Dim w As String = a + d
  

Converting an integer into a decimal and vice versa

This is a simple way to convert an integer into a decimal.
This is also a simple way of converting a decimal into an integer
 Dim GPA As Decimal
  
 GPA.Text = CInt(GPA)
  

 Dim myAge As Integer
  
 myAge.Text = CDec(myAge)
  

Converting a number variable into a string

To convert a number variable to a string in VB, there are two ways. This way is the faster, simpler way:


 Dim txtBox as Integer
  
  txtBox.Text = CStr(txtBox)
  

How to set string, boolean, integer, and decimal variables

Setting a string variable.
 Dim aString As String
  
aString = "Hello World"
Setting a boolean variable
 Dim runningVB As Boolean
  
 ' Check to see if program is running on Visual Basic engine.
  
 If scriptEngine = "VB" Then
  
   runningVB = True
  
 End If
  
Setting an integer variable
 Dim k As Integer
  
 ' The following statement sets k to 6.
  
 k = 5.9
  
 ' The following statement sets k to 4
  
 k = 4.5
  
 ' The following statement sets k to 6
  
 k = 5.5
  
Setting a decimal variable
 Dim d1, d2 As Decimal
d1 = 2.3
d2 = 4.8