1.11M Members

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.

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);
}
}
}
}

Try the constant 1.8 , instead of the fraction.

You are right MosaicFuneral. If we can avoid division we must!
I left 5/9 and 9/5 in because it is clearer to understand. I a real situation I would also use 1.8 and 0.55555.
Btw. the absolute temp constants are in a way not correct either!
Real absolute temps are negative, but here the calculations done are correct.

Isn't it about time forums rewarded their contributors?

Earn rewards points for helping others. Gain kudos. Cash out. Get better answers yourself.

It's as simple as contributing editorial or replying to discussions labeled or OP Kudos

You
This is an OP Kudos discussion and contributors may be rewarded
Post:
View similar articles that have also been tagged: