Computer Science 101

with:  Erik Oosterwal

Search for specific programs or algorithms:
Custom Search





Temperature Conversion


Temperature conversion algorithms are some of the easiest programs to write and every first year computer programming student will have had to write one at least once in their life.  The most difficult things about the algorithm is the simple algebraic formula y=mx+b, which rears its ugly head from high school math class, and trying to remember if you subtract or add the 32 degrees before or after multiplying by the slope factor.

If you recall, y=mx+b is used to describe a straight line on a plane where y is a function of x, m is the slope of the line (rise divided by run), and b is the value of y where the line crosses the y axis.

If we know the temperature in fahrenheit and want to convert to celsius (also known as centigrade), we use this conversion:

     °C = 5/9(°F-32)

To convert celsius back to fahrenheit we use this formula:

     °F = 9/5°C + 32

The kelvin scale uses the same rate of change between degrees (slope) as celsius, but the y crossing point is much higher.  To convert celsius to kelvin simply add 273.18 to °C.  To convert from kelvin back to celsius, simply subtract 273.18 from °K.

Some sample pseudo-code appears below:



//* subroutine to convert celsius to fahrenheit *//
function c2f(temperature)(
	c2f = temperature * 9 / 5 + 32
)



//* subroutine to convert fahrenheit to celsius *//
function f2c(temperature)(
	f2c = (temperature-32) * 5 / 9
)



//* subroutine to convert celsius to kelvin *//
function c2k(temperature)(
	c2k = temperature + 273.18
)





Discuss computer algorithms and other computer science topics at the Computer Algorithms blog page.

All code and original algorithms are © Erik Oosterwal - 1987-2008
Computer Science 101

Dressing for Success