1,105,427 Community Members

Temperature conversion class in C#

Member Avatar
Reputation Points: 2,066 [?]
Q&As Helped to Solve: 908 [?]
Skill Endorsements: 46 [?]
 
0
 

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);
            }
            Console.ReadKey();
        }
    }
}
Member Avatar
MosaicFuneral
Nearly a Posting Virtuoso
1,285 posts since Nov 2008
Reputation Points: 812 [?]
Q&As Helped to Solve: 157 [?]
Skill Endorsements: 11 [?]
 
0
 

Try the constant 1.8 , instead of the fraction.

Member Avatar
ddanbe
Posting Expert
5,355 posts since Oct 2008
Reputation Points: 2,066 [?]
Q&As Helped to Solve: 908 [?]
Skill Endorsements: 46 [?]
Featured
 
0
 

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.

You
Post:
Start New Discussion
View similar articles that have also been tagged: