Programming Fundamentals/Conditions/VB.NET
Jump to navigation
Jump to search
conditions.vb
[edit | edit source]' This program asks the user to select Fahrenheit or Celsius conversion
' and input a given temperature. Then the program converts the given
' temperature and displays the result.
'
' References:
' https://www.mathsisfun.com/temperature-conversion.html
' https://en.wikibooks.org/wiki/Visual_Basic_.NET
Imports System
Public Module MyProgram
Sub Main
' Main could either be an If-Else structure or a Select-Case structure
Dim Choice As String
Dim Temperature As Double
Dim Result As Double
Console.WriteLine("Enter F to convert to Fahrenheit or C to convert to Celsius:")
Choice = Console.ReadLine()
' If-Else approach
If Choice = "C" Or Choice = "c" Then
Temperature = GetTemperature("Fahrenheit")
Result = CalculateCelsius(Temperature)
DisplayResult(Temperature, "Fahrenheit", Result, "Celsius")
ElseIf Choice = "F" Or Choice = "f" Then
Temperature = GetTemperature("Celsius")
Result = CalculateFahrenheit(Temperature)
DisplayResult(Temperature, "Celsius", Result, "Fahrenheit")
Else
Console.WriteLine("You must enter C to convert to Celsius or F to convert to Fahrenheit!")
End If
' Select-Case approach
Select Choice
Case "C", "c"
Temperature = GetTemperature("Fahrenheit")
Result = CalculateCelsius(Temperature)
DisplayResult(Temperature, "Fahrenheit", Result, "Celsius")
Case "F", "f"
Temperature = GetTemperature("Celsius")
Result = CalculateFahrenheit(Temperature)
DisplayResult(Temperature, "Celsius", Result, "Fahrenheit")
Case Else
Console.WriteLine("You must enter C to convert to Celsius or F to convert to Fahrenheit!")
End Select
End Sub
Function GetTemperature(Label as String) As Double
Dim Input As String
Dim Temperature As Double
Console.WriteLine("Enter " + Label + " temperature:")
Input = Console.ReadLine()
Temperature = Convert.ToDouble(Input)
Return Temperature
End Function
Function CalculateCelsius(Fahrenheit As Double) As Double
Dim Celsius As Double
Celsius = (Fahrenheit - 32) * 5 / 9
Return Celsius
End Function
Function CalculateFahrenheit(Celsius As Double) As Double
Dim Fahrenheit As Double
Fahrenheit = Celsius * 9 / 5 + 32
Return Fahrenheit
End Function
Sub DisplayResult(Temperature As Double, FromLabel As String, Result As Double, ToLabel As String)
Console.WriteLine(Temperature.ToString() + "° " + FromLabel + " is " + Result.ToString() + "° " + ToLabel)
End Sub
End Module
Try It
[edit | edit source]Copy and paste the code above into one of the following free online development environments or use your own VB.NET compiler / interpreter / IDE.