Class to convert between Celcius, Fahrenheit and Kelvin temperatures.
Set one temperature and automatically get the other two.
This class makes use of properties. See the code snippet for details.
A short main program is added to exercise the Temperature class by printing a conversion table between celsius and fahrenheit.
Temperature conversion class in C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Console_Temperature
{
class Temperature
{
private const double cAbsTempC = 273.15;//absolute temperature in Celcius
private const double cAbsTempF = 459.67;//absolute temperature in Fahrenheit
private double _Kelvin = 0.0;
public Temperature(){}
public Temperature(double kelvintemp)
{
_Kelvin = kelvintemp;
}
public double Celcius
{
get { return _Kelvin - cAbsTempC; }
set { _Kelvin = value + cAbsTempC; }
}
public double Fahrenheit
{
get { return _Kelvin*9/5 - cAbsTempF; }
set { _Kelvin = (value + cAbsTempC)*5/9; }
}
public double Kelvin
{
get { return _Kelvin; }
set { _Kelvin = value; }
}
}
class Program
{
static void Main(string[] args)
{
// print a table from 0 to 10 degrees C,
// with the conversion to Fahrenheit degrees,
// using the Temperature class
Temperature temp = new Temperature();
Console.WriteLine("Celcius \t Fahrenheit");
Console.WriteLine();
for (int i = 0; i <= 10; i++)
{
temp.Celcius = i;
Console.WriteLine("{0} \t {1}", temp.Celcius, temp.Fahrenheit);
}
Console.ReadKey();
}
}
}
MosaicFuneral 812 Nearly a Posting Virtuoso
ddanbe 2,724 Professional Procrastinator Featured Poster
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.