C# Variable Basics Using Temperature Conversion Fahrenheit and Celsius

Here is a brief introduction to variable within C#.  We will be using temperature conversions to demonstrate variable declaration, usage, and formatting. Simply copy and paste the code into any new Microsoft Visual C# console application and you should be good to run this application.

/*This is a console application to introduction to variables.

Every program requires a heading, which is below. The fields

will vary according to the class or organization you are

creating this program. For this class we will use temperature

conversions.

 

What is a variable? Think of a variable as a container that

holds items.

 

Program: Introduction to Variables

Programmer: Mike Kniaziewicz

Date: February 26, 2012

Version: 1.0.0 */

using  System;
using  System.Collections.Generic;
using  System.Linq;
using System.Text;

namespace Introduction_to_Variables //namespace is a system level object

{

class Program

{

//Every C, C++, and C# will have a Main method

static void Main(string[] args)

{

/*This is where you declare variables to be used
I generally place the first letter of the variable type before the variable for readability in the Main function. Here are the formulas we will be using:
C = (F – 32) * 5/9
F = C * 9/5 + 32*/

double dcelcius, dfahrenheit;

string scelcius;

Console.WriteLine(“Enter a temperature to convert to celcius:”);

//always returns a string value,so you will need to parse (convert) it to a double

dfahrenheit =double.Parse(Console.ReadLine());

/* For math always remember Please (Parenthesis) Excuse(Exponents)

My (Multiplication) Dear (Division) Aunt (Addition)  Sallie (Subtraction)*/

dcelcius = (dfahrenheit – 32) * 5 / 9;

//Format the double output, so there are 0 decimal places

Console.WriteLine(“You entered {0:F0} F, celcius is {1:F0}\n”, dfahrenheit, dcelcius);

//Convert Celcius to Fahrenheit; however do not convert the string

//until performing the math

Console.WriteLine(“Enter a temperature to convert to Fahrenheit:”);

scelcius =Console.ReadLine();

dfahrenheit =double.Parse(scelcius) * 9 / 5 + 32;

Console.WriteLine(“You entered {0} C, fahrenheit is {1:F0}\n”, scelcius, dfahrenheit);

//Console.ReadKey will keep the Console application open waiting for a keyboard response

Console.ReadKey();

}

}

}

 

Comments are closed.