Temperature conversion: Difference between revisions

From Rosetta Code
Content added Content deleted
(Added Prolog)
 
(22 intermediate revisions by 14 users not shown)
Line 35: Line 35:


=={{header|11l}}==
=={{header|11l}}==
<lang 11l>V k = 21.0
<syntaxhighlight lang="11l">V k = 21.0
print(‘K ’k)
print(‘K ’k)
print(‘C ’(k - 273.15))
print(‘C ’(k - 273.15))
print(‘F ’(k * 1.8 - 459.67))
print(‘F ’(k * 1.8 - 459.67))
print(‘R ’(k * 1.8))</lang>
print(‘R ’(k * 1.8))</syntaxhighlight>


{{out}}
{{out}}
Line 53: Line 53:
Use of packed decimal arithmetic
Use of packed decimal arithmetic
(ZAP,SP,MP,DP,UNPK,CVD,EDMK opcodes).
(ZAP,SP,MP,DP,UNPK,CVD,EDMK opcodes).
<lang>* Temperature conversion 10/09/2015
<syntaxhighlight lang="text">* Temperature conversion 10/09/2015
TEMPERAT CSECT
TEMPERAT CSECT
USING TEMPERAT,R15
USING TEMPERAT,R15
Line 125: Line 125:
EDMASKN DC X'402021204B202060' CL8 5num
EDMASKN DC X'402021204B202060' CL8 5num
YREGS
YREGS
END TEMPERAT</lang>
END TEMPERAT</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 146: Line 146:


=={{header|8th}}==
=={{header|8th}}==
<lang forth>: KtoC \ n -- n
<syntaxhighlight lang="forth">: KtoC \ n -- n
273.15 n:-
273.15 n:-
;
;
Line 178: Line 178:
bye
bye
;
;
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>>8th temp.8th 21
<pre>>8th temp.8th 21
Line 189: Line 189:
=={{header|Action!}}==
=={{header|Action!}}==
{{libheader|Action! Tool Kit}}
{{libheader|Action! Tool Kit}}
<lang Action!>INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit
<syntaxhighlight lang="action!">INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit


PROC K2C(REAL POINTER k,c)
PROC K2C(REAL POINTER k,c)
Line 241: Line 241:
ValR("373.15",k) Test("Water boils",k)
ValR("373.15",k) Test("Water boils",k)
RETURN
RETURN
</lang>
</syntaxhighlight>
{{out}}
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Temperature_conversion.png Screenshot from Atari 8-bit computer]
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Temperature_conversion.png Screenshot from Atari 8-bit computer]
Line 266: Line 266:
=={{header|Ada}}==
=={{header|Ada}}==


<lang Ada>with Ada.Float_Text_IO, Ada.Text_IO; use Ada.Float_Text_IO, Ada.Text_IO;
<syntaxhighlight lang="ada">with Ada.Float_Text_IO, Ada.Text_IO; use Ada.Float_Text_IO, Ada.Text_IO;


procedure Temperatur_Conversion is
procedure Temperatur_Conversion is
Line 279: Line 279:
Put("F: "); Put(F, Fore => 4, Aft => 2, Exp => 0); New_Line;-- F: dddd.dd
Put("F: "); Put(F, Fore => 4, Aft => 2, Exp => 0); New_Line;-- F: dddd.dd
Put("R: "); Put(R, Fore => 4, Aft => 2, Exp => 0); New_Line;-- R: dddd.dd
Put("R: "); Put(R, Fore => 4, Aft => 2, Exp => 0); New_Line;-- R: dddd.dd
end;</lang>
end;</syntaxhighlight>


{{out}}
{{out}}
Line 290: Line 290:


=={{header|Aime}}==
=={{header|Aime}}==
<lang aime>void
<syntaxhighlight lang="aime">void
show(integer symbol, real temperature)
show(integer symbol, real temperature)
{
{
Line 309: Line 309:


return 0;
return 0;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>aime$ aime -a tmp/tconvert 300
<pre>aime$ aime -a tmp/tconvert 300
Line 318: Line 318:


=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
<lang algol68>
<syntaxhighlight lang="algol68">
BEGIN
BEGIN
REAL kelvin;
REAL kelvin;
Line 326: Line 326:
printf ((f, kelvin, 9.0 * kelvin / 5.0, "R"));
printf ((f, kelvin, 9.0 * kelvin / 5.0, "R"));
printf ((f, kelvin, 9.0 * kelvin / 5.0 - 459.67, "F"))
printf ((f, kelvin, 9.0 * kelvin / 5.0 - 459.67, "F"))
END</lang>
END</syntaxhighlight>
{{out}}
{{out}}
<pre>$ echo 21 | a68g Temperature_conversion.a68
<pre>$ echo 21 | a68g Temperature_conversion.a68
Line 336: Line 336:
=={{header|ALGOL-M}}==
=={{header|ALGOL-M}}==
If the temperature in Kelvin is a whole number, you should type a decimal point after it (e.g. <code>290.</code>): <code>290</code> with no decimal point will be interpreted as 0.29 rather than 290.0.
If the temperature in Kelvin is a whole number, you should type a decimal point after it (e.g. <code>290.</code>): <code>290</code> with no decimal point will be interpreted as 0.29 rather than 290.0.
<lang algol>BEGIN
<syntaxhighlight lang="algol">BEGIN
DECIMAL K, C, F, R;
DECIMAL K, C, F, R;
WRITE( "Temperature in Kelvin:" );
WRITE( "Temperature in Kelvin:" );
Line 347: Line 347:
WRITE( F, " degrees Fahrenheit" );
WRITE( F, " degrees Fahrenheit" );
WRITE( R, " degrees Rankine" );
WRITE( R, " degrees Rankine" );
END</lang>
END</syntaxhighlight>

=={{header|ALGOL W}}==
<syntaxhighlight lang="algolw">
begin % convert Kelvin to Celcius, Farenheit and Rankine %
real kelvin, rankine;
write( "Kelvin: " );
read( kelvin );
rankine := ( 9 * kelvin ) / 5;
r_format := "A"; r_w := 8; r_d := 2; s_w := 0; % set output formating %
write( kelvin, " Kelvin is:" );
write( " ", kelvin - 273.15, " Celcius" );
write( " ", rankine, " Rankine" );
write( " ", rankine - 459.67, " Farenheit" )
end.
</syntaxhighlight>


=={{header|Amazing Hopper}}==
=={{header|Amazing Hopper}}==
<syntaxhighlight lang="amazing hopper">
<lang Amazing Hopper>
/* MISTRAL - a flavour of Hopper */
/* MISTRAL - a flavour of Hopper */


Line 378: Line 393:
FUNCIÓN( Conversión Kelvin a Rankine, k)
FUNCIÓN( Conversión Kelvin a Rankine, k)
RETORNAR ( {k} POR (1.8), REDONDEADO AL DECIMAL(2) )
RETORNAR ( {k} POR (1.8), REDONDEADO AL DECIMAL(2) )
</syntaxhighlight>
</lang>
<p>Another version:</p>
<p>Another version:</p>
<syntaxhighlight lang="amazing hopper">
<lang Amazing Hopper>
/* MISTRAL - a flavour of Hopper */
/* MISTRAL - a flavour of Hopper */


Line 393: Line 408:
IMPRIMIR("RANKINE : ",temperatura, POR '1.8', NL)
IMPRIMIR("RANKINE : ",temperatura, POR '1.8', NL)
FINALIZAR
FINALIZAR
</syntaxhighlight>
</lang>
<p>Another version:</p>
<p>Another version:</p>
<syntaxhighlight lang="amazing hopper">
<lang Amazing Hopper>
#include <mistral.h>
#include <mistral.h>


Line 407: Line 422:
"RANKINE : ", {temperatura} POR '1.8', NL)
"RANKINE : ", {temperatura} POR '1.8', NL)
FINALIZAR
FINALIZAR
</syntaxhighlight>
</lang>
<p>Or another (and last) version:</p>
<syntaxhighlight lang="amazing hopper">
#include <mistral.h>

INICIAR:
TAMAÑO DE MEMORIA 20
temperatura=0, rankine=0
RECIBIR PARÁMETRO NUMÉRICO(2), GUARDAR EN (temperatura);
IMPRIMIR("KELVIN : ", temperatura, NL,\
"CELSIUS : ", {temperatura} MENOS '273.15', NL,\
"FAHRENHEIT : ", {temperatura} POR '1.8' ---RESPALDE EN 'rankine'--- MENOS '459.67', NL,\
"RANKINE : ", rankine, NL)
FINALIZAR
</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 426: Line 455:
=={{header|APL}}==
=={{header|APL}}==
Given a temperature in Kelvin, prints the equivalent in Kelvin, Celsius, Fahrenheit, and Rankine (in that order).
Given a temperature in Kelvin, prints the equivalent in Kelvin, Celsius, Fahrenheit, and Rankine (in that order).
<lang apl> CONVERT←{⍵,(⍵-273.15),(R-459.67),(R←⍵×9÷5)}</lang>
<syntaxhighlight lang="apl"> CONVERT←{⍵,(⍵-273.15),(R-459.67),(R←⍵×9÷5)}</syntaxhighlight>
{{out}}
{{out}}
<lang apl> CONVERT 21
<syntaxhighlight lang="apl"> CONVERT 21
21 ¯252.15 ¯421.87 37.8</lang>
21 ¯252.15 ¯421.87 37.8</syntaxhighlight>
The "high minus" character <tt>¯</tt> is used in APL to mark negative numbers, preventing any possible confusion with <tt>-</tt> (the subtraction operator).
The "high minus" character <tt>¯</tt> is used in APL to mark negative numbers, preventing any possible confusion with <tt>-</tt> (the subtraction operator).


=={{header|AppleScript}}==
=={{header|AppleScript}}==
{{Trans|JavaScript}} ( ES6 version )
{{Trans|JavaScript}} ( ES6 version )
<lang AppleScript>use framework "Foundation" -- Yosemite onwards, for the toLowerCase() function
<syntaxhighlight lang="applescript">use framework "Foundation" -- Yosemite onwards, for the toLowerCase() function


-- KELVIN TO OTHER SCALE -----------------------------------------------------
-- KELVIN TO OTHER SCALE -----------------------------------------------------
Line 546: Line 575:
((ca's NSString's stringWithString:(str))'s ¬
((ca's NSString's stringWithString:(str))'s ¬
lowercaseStringWithLocale:(ca's NSLocale's currentLocale())) as text
lowercaseStringWithLocale:(ca's NSLocale's currentLocale())) as text
end toLower</lang>
end toLower</syntaxhighlight>
{{Out}}
{{Out}}
<pre>K 21.0
<pre>K 21.0
Line 557: Line 586:
Or of course:
Or of course:


<lang applescript>on convertFromKelvin(kelvinValue)
<syntaxhighlight lang="applescript">on convertFromKelvin(kelvinValue)
return ("K" & tab & (kelvinValue as real)) & ¬
return ("K" & tab & (kelvinValue as real)) & ¬
(linefeed & "C" & tab & (kelvinValue - 273.15)) & ¬
(linefeed & "C" & tab & (kelvinValue - 273.15)) & ¬
Line 564: Line 593:
end convertFromKelvin
end convertFromKelvin


convertFromKelvin(21)</lang>
convertFromKelvin(21)</syntaxhighlight>


Vanilla AppleScript actually has a handful of built-in measurement unit coercions, including three for converting between temperatures in Kelvin, Celsius, and Fahrenheit. There isn't one for Rankine, but it's an easy calculation from Kelvin:
Vanilla AppleScript actually has a handful of built-in measurement unit coercions, including three for converting between temperatures in Kelvin, Celsius, and Fahrenheit. There isn't one for Rankine, but it's an easy calculation from Kelvin:


<lang applescript>on convertFromKelvin(kelvinValue)
<syntaxhighlight lang="applescript">on convertFromKelvin(kelvinValue)
set kelvinMeasurement to kelvinValue as degrees Kelvin
set kelvinMeasurement to kelvinValue as degrees Kelvin
Line 581: Line 610:
end convertFromKelvin
end convertFromKelvin


convertFromKelvin(21)</lang>
convertFromKelvin(21)</syntaxhighlight>


As from macOS 10.12 Sierra, macOS's Foundation framework too offers "Units and Measurement" classes and methods, which can be accessed from AppleScript using ASObjC code. They offer many more categories and units, although it's usually easier, faster, and more efficient (and occasionally more accurate!) to look up the conversion formulae on Wikipedia and write the math directly into the scripts, as above.
As from macOS 10.12 Sierra, macOS's Foundation framework too offers "Units and Measurement" classes and methods, which can be accessed from AppleScript using ASObjC code. They offer many more categories and units, although it's usually easier, faster, and more efficient (and occasionally more accurate!) to look up the conversion formulae on Wikipedia and write the math directly into the scripts, as above.


<lang applescript>use AppleScript version "2.5" -- macOS 10.12 (Sierra) or later
<syntaxhighlight lang="applescript">use AppleScript version "2.5" -- macOS 10.12 (Sierra) or later
use framework "Foundation"
use framework "Foundation"


Line 618: Line 647:
end convertFromKelvin
end convertFromKelvin


convertFromKelvin(21)</lang>
convertFromKelvin(21)</syntaxhighlight>


=={{header|Arturo}}==
=={{header|Arturo}}==


<lang rebol>convertKelvins: function [k][
<syntaxhighlight lang="rebol">convertKelvins: function [k][
#[
#[
celcius: k - 273.15
celcius: k - 273.15
Line 630: Line 659:
]
]


print convertKelvins 100</lang>
print convertKelvins 100</syntaxhighlight>


{{out}}
{{out}}


<pre>[celcius:-173.15 fahrenheit:-279.67 rankine:180.0]</pre>
<pre>[celcius:-173.15 fahrenheit:-279.67 rankine:180.0]</pre>

=={{header|Asymptote}}==
<syntaxhighlight lang="Asymptote">void convKelvin(real K) {
write("K = " + string(K));
write("C = " + string(K - 273.15));
write("F = " + string((K - 273.15) * 1.8 + 32.0));
write("R = " + string(K * 1.8));
}

convKelvin(0.0);
write("");
convKelvin(21.0);</syntaxhighlight>


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
<lang AutoHotkey>MsgBox, % "Kelvin:`t`t 21.00 K`n"
<syntaxhighlight lang="autohotkey">MsgBox, % "Kelvin:`t`t 21.00 K`n"
. "Celsius:`t`t" kelvinToCelsius(21) " C`n"
. "Celsius:`t`t" kelvinToCelsius(21) " C`n"
. "Fahrenheit:`t" kelvinToFahrenheit(21) " F`n"
. "Fahrenheit:`t" kelvinToFahrenheit(21) " F`n"
Line 653: Line 694:
{
{
return, round(k * 1.8, 2)
return, round(k * 1.8, 2)
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>Kelvin: 21.00 K
<pre>Kelvin: 21.00 K
Line 661: Line 702:


=={{header|AutoIt}}==
=={{header|AutoIt}}==
<lang AutoIt>; ### USAGE - TESTING PURPOSES ONLY
<syntaxhighlight lang="autoit">; ### USAGE - TESTING PURPOSES ONLY


Local Const $_KELVIN = 21
Local Const $_KELVIN = 21
Line 680: Line 721:
Return Round($degrees * 1.8, 2)
Return Round($degrees * 1.8, 2)
EndSelect
EndSelect
EndFunc ;==> Kelvin</lang>
EndFunc ;==> Kelvin</syntaxhighlight>
{{out}}
{{out}}
<pre>Kelvin: 21°
<pre>Kelvin: 21°
Line 689: Line 730:
=={{header|AWK}}==
=={{header|AWK}}==
"Interactive" version, reading from stdin only:
"Interactive" version, reading from stdin only:
<lang AWK># syntax: AWK -f TEMPERATURE_CONVERSION.AWK
<syntaxhighlight lang="awk"># syntax: AWK -f TEMPERATURE_CONVERSION.AWK
BEGIN {
BEGIN {
while (1) {
while (1) {
Line 707: Line 748:
}
}
exit(0)
exit(0)
}</lang>
}</syntaxhighlight>


"Regular" version, reading from input-file(s). <br>
"Regular" version, reading from input-file(s). <br>
Line 713: Line 754:


{{works with|gawk}} BEGINFILE is a gawk-extension
{{works with|gawk}} BEGINFILE is a gawk-extension
<lang AWK># usage: gawk -f temperature_conversion.awk input.txt -
<syntaxhighlight lang="awk"># usage: gawk -f temperature_conversion.awk input.txt -


BEGIN { print("# Temperature conversion\n") }
BEGIN { print("# Temperature conversion\n") }
Line 732: Line 773:


END { print("# Bye.") }
END { print("# Bye.") }
</syntaxhighlight>
</lang>


{{out|Input}} the numeric value of the first word in each line is used as input for the conversion
{{out|Input}} the numeric value of the first word in each line is used as input for the conversion
Line 805: Line 846:


=={{header|BASIC}}==
=={{header|BASIC}}==
<syntaxhighlight lang="basic">10 REM TRANSLATION OF AWK VERSION

<lang basic>
10 REM TRANSLATION OF AWK VERSION
20 INPUT "KELVIN DEGREES",K
20 INPUT "KELVIN DEGREES",K
30 IF K <= 0 THEN END: REM A VALUE OF ZERO OR LESS WILL END PROGRAM
30 IF K <= 0 THEN END: REM A VALUE OF ZERO OR LESS WILL END PROGRAM
Line 817: Line 856:
90 PRINT F; " DEGREES FAHRENHEIT"
90 PRINT F; " DEGREES FAHRENHEIT"
100 PRINT R; " DEGREES RANKINE"
100 PRINT R; " DEGREES RANKINE"
110 GOTO 20
110 GOTO 20</syntaxhighlight>
</lang>


==={{header|QBasic}}===
==={{header|Applesoft BASIC}}===
The [[#Chipmunk Basic|Chipmunk_Basic]] solution works without any changes.
<lang QBasic>DO
INPUT "Kelvin degrees (>=0): ", K
LOOP UNTIL K >= 0


==={{header|BASIC256}}===
PRINT "K = " + STR$(K)
<syntaxhighlight lang="basic256">do
PRINT "C = " + STR$(K - 273.15)
print "Kelvin degrees (>=0): ";
PRINT "F = " + STR$(K * 1.8 - 459.67)
input K
PRINT "R = " + STR$(K * 1.8)
until K>=0
END</lang>


print "K = " + string(K)
==={{header|True BASIC}}===
print "C = " + string(K - 273.15)
print "F = " + string(K * 1.8 - 459.67)
print "R = " + string(K * 1.8)</syntaxhighlight>

==={{header|BBC BASIC}}===
<syntaxhighlight lang="bbcbasic">REPEAT
INPUT "Kelvin degrees (>=0): " K
UNTIL K>=0
@%=&20208
PRINT '"K = " K
PRINT "C = " K - 273.15
PRINT "F = " K * 1.8 - 459.67
PRINT "R = " K * 1.8
END</syntaxhighlight>
{{out}}
<pre>Kelvin degrees (>=0): 21

K = 21.00
C = -252.15
F = -421.87
R = 37.80</pre>

==={{header|Chipmunk Basic}}===
{{works with|Chipmunk Basic|3.6.4}}
{{works with|QBasic}}
{{works with|QBasic}}
{{works with|QuickBasic}}
<lang qbasic>DO
{{works with|Applesoft BASIC}}
PRINT "Kelvin degrees (>=0): ";
{{works with|BASICA}}
INPUT K
{{works with|GW-BASIC}}
LOOP UNTIL K >= 0
{{works with|IS-BASIC}}
{{works with|Minimal BASIC}}
{{works with|MSX BASIC|any}}
{{works with|Run BASIC}}
{{works with|Just BASIC}}
{{works with|Liberty BASIC}}
<syntaxhighlight lang="qbasic">10 CLS : REM 10 HOME for Applesoft BASIC : DELETE for Minimal BASIC
20 PRINT "Kelvin Degrees ";
30 INPUT K
40 IF K <= 0 THEN 130
50 LET C = K-273.15
60 LET F = K*1.8-459.67
70 LET R = K*1.8
80 PRINT K;" Kelvin is equivalent to"
90 PRINT C;" Degrees Celsius"
100 PRINT F;" Degrees Fahrenheit"
110 PRINT R;" Degrees Rankine"
120 GOTO 20
130 END</syntaxhighlight>


==={{header|FreeBASIC}}===
PRINT "K = "; STR$(K)
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64
PRINT "C = "; STR$(K - 273.15)
PRINT "F = "; STR$(K * 1.8 - 459.67)
PRINT "R = "; STR$(K * 1.8)
END</lang>


Sub convKelvin(temp As Double)
==={{header|Yabasic}}===
Dim f As String = "####.##"
<lang yabasic>repeat
Print Using f; temp;
input "Kelvin degrees (>=0): " K
Print " degrees Kelvin"
until K >= 0
Print Using f; temp - 273.15;
Print " degrees Celsius"
Print Using f; (temp - 273.15) * 1.8 + 32.0;
Print " degrees Fahreneit"
Print Using f; (temp - 273.15) * 1.8 + 32.0 + 459.67;
Print " degrees Rankine"
End Sub


convKelvin(0.0)
print "K = " + str$(K)
Print
print "C = " + str$(K - 273.15)
convKelvin(21.0)
print "F = " + str$(K * 1.8 - 459.67)
Print
print "R = " + str$(K * 1.8)
Print "Press any key to quit"
end</lang>
Sleep</syntaxhighlight>
{{out}}
<pre> 0.00 degrees Kelvin
-273.15 degrees Celsius
-459.67 degrees Fahreneit
0.00 degrees Rankine

21.00 degrees Kelvin
-252.15 degrees Celsius
-421.87 degrees Fahreneit
37.80 degrees Rankine</pre>

==={{header|Gambas}}===
<syntaxhighlight lang="gambas">Public Sub Form_Open()
Dim fKelvin As Float

fKelvin = InputBox("Enter a Kelvin value", "Kelvin converter")

Print "Kelvin =\t" & Format(Str(fKelvin), "#.00")
Print "Celsius =\t" & Format(Str(fKelvin - 273.15), "#.00")
Print "Fahrenheit =\t" & Format(Str(fKelvin * 1.8 - 459.67), "#.00")
Print "Rankine =\t" & Format(Str(fKelvin * 1.8), "#.00")

End</syntaxhighlight>
{{out}}
<pre>Kelvin = 21.00
Celsius = -252.15
Fahrenheit = -421.87
Rankine = 37.80</pre>

==={{header|GW-BASIC}}===
The [[#Chipmunk Basic|Chipmunk_Basic]] solution works without any changes.


==={{header|IS-BASIC}}===
==={{header|IS-BASIC}}===
<lang IS-BASIC>100 INPUT PROMPT "Kelvin degrees: ":K
<syntaxhighlight lang="is-basic">100 INPUT PROMPT "Kelvin degrees: ":K
110 PRINT K;TAB(10);"Kelvin is equivalent to"
110 PRINT K;TAB(10);"Kelvin is equivalent to"
120 PRINT K-273.15;TAB(10);"Degrees Celsius"
120 PRINT K-273.15;TAB(10);"Degrees Celsius"
130 PRINT K*1.8-459.67;TAB(10);"Degrees Fahrenheit"
130 PRINT K*1.8-459.67;TAB(10);"Degrees Fahrenheit"
140 PRINT K*1.8;TAB(10);"Degrees Rankine"</lang>
140 PRINT K*1.8;TAB(10);"Degrees Rankine"</syntaxhighlight>

==={{header|Liberty BASIC}}===
<syntaxhighlight lang="liberty basic">Do
Input "Kelvin degrees (>=0): ";K
Loop Until (K >= 0)

Print "K = ";K
Print "C = ";(K - 273.15)
Print "F = ";(K * 1.8 - 459.67)
Print "R = ";(K * 1.8)
End</syntaxhighlight>
{{out}}
<pre>Kelvin degrees (>=0): 21
K = 21
C = -252.15
F = -421.87
R = 37.8</pre>

==={{header|Minimal BASIC}}===
The [[#Chipmunk Basic|Chipmunk_Basic]] solution works without any changes.

==={{header|MSX Basic}}===
The [[#Chipmunk Basic|Chipmunk_Basic]] solution works without any changes.

==={{header|PureBasic}}===
<syntaxhighlight lang="purebasic">Procedure.d Kelvin2Celsius(tK.d) : ProcedureReturn tK-273.15 : EndProcedure
Procedure.d Kelvin2Fahrenheit(tK.d) : ProcedureReturn tK*1.8-459.67 : EndProcedure
Procedure.d Kelvin2Rankine(tK.d) : ProcedureReturn tK*1.8 : EndProcedure

OpenConsole()
Repeat
Print("Temperatur Kelvin? ") : Kelvin.d = ValD(Input())
PrintN("Conversion:")
PrintN(#TAB$+"Celsius "+#TAB$+RSet(StrD(Kelvin2Celsius(Kelvin),2),8,Chr(32)))
PrintN(#TAB$+"Fahrenheit"+#TAB$+RSet(StrD(Kelvin2Fahrenheit(Kelvin),2),8,Chr(32)))
PrintN(#TAB$+"Rankine "+#TAB$+RSet(StrD(Kelvin2Rankine(Kelvin),2),8,Chr(32)))
PrintN("ESC = End.")
Repeat
k$=Inkey() : Delay(50) : If RawKey()=#ESC : End : EndIf
Until RawKey()
ForEver</syntaxhighlight>
<pre>Temperatur Kelvin? 21
Conversion:
Celsius -252.15
Fahrenheit -421.87
Rankine 37.80
ESC = End.</pre>

==={{header|QB64}}===
<syntaxhighlight lang="qb64">Dim As Single Celsius, Kelvin, Fahrenheit, Rankine

Kelvin = -300
While Kelvin = -300
Input "Please type Kelvin temperature...or -300 to quit ", Kelvin
If Kelvin = -300 Then
End
Else

Celsius = Kelvin - 273.15
Fahrenheit = ((9 / 5) * Celsius) + 32
Rankine = Fahrenheit + 459.67
End If
Print " Celsius", "Fahrenheit", "Kelvin", "Rankine "
Print Celsius, Fahrenheit, Kelvin, Rankine
Kelvin = -300
Wend</syntaxhighlight>

==={{header|QBasic}}===
<syntaxhighlight lang="qbasic">DO
INPUT "Kelvin degrees (>=0): ", K
LOOP UNTIL K >= 0

PRINT "K = " + STR$(K)
PRINT "C = " + STR$(K - 273.15)
PRINT "F = " + STR$(K * 1.8 - 459.67)
PRINT "R = " + STR$(K * 1.8)
END</syntaxhighlight>

==={{header|Quite BASIC}}===
<syntaxhighlight lang="qbasic">10 PRINT "Kelvin Degrees ";
20 INPUT ""; K
30 IF K <= 0 THEN END
40 LET C = K-273.15
50 LET F = K*1.8-459.67
60 LET R = K*1.8
70 PRINT K;" Kelvin is equivalent to"
80 PRINT C;" Degrees Celsius"
90 PRINT F;" Degrees Fahrenheit"
100 PRINT R;" Degrees Rankine"
110 GOTO 10</syntaxhighlight>


==={{header|Sinclair ZX81 BASIC}}===
==={{header|Sinclair ZX81 BASIC}}===
<lang basic>10 PRINT "ENTER A TEMPERATURE IN KELVINS"
<syntaxhighlight lang="basic">10 PRINT "ENTER A TEMPERATURE IN KELVINS"
20 INPUT K
20 INPUT K
30 PRINT K;" KELVINS ="
30 PRINT K;" KELVINS ="
40 PRINT K-273.15;" DEGREES CELSIUS"
40 PRINT K-273.15;" DEGREES CELSIUS"
50 PRINT K*1.8-459.67;" DEGREES FAHRENHEIT"
50 PRINT K*1.8-459.67;" DEGREES FAHRENHEIT"
60 PRINT K*1.8;" DEGREES RANKINE"</lang>
60 PRINT K*1.8;" DEGREES RANKINE"</syntaxhighlight>


==={{Header|Tiny BASIC}}===
==={{Header|Tiny BASIC}}===
<lang tiny basic>
<syntaxhighlight lang="tiny basic">
PRINT "Temperature in Kelvin?"
PRINT "Temperature in Kelvin?"
INPUT K
INPUT K
Line 879: Line 1,084:
PRINT C," Celsius"
PRINT C," Celsius"
PRINT F," Fahrenheit"
PRINT F," Fahrenheit"
PRINT R," Rankine"</lang>
PRINT R," Rankine"</syntaxhighlight>


=={{header|BASIC256}}==
==={{header|True BASIC}}===
{{works with|QBasic}}
<lang basic256>
<syntaxhighlight lang="qbasic">DO
do
print "Kelvin degrees (>=0): ";
PRINT "Kelvin degrees (>=0): ";
input K
INPUT K
until K>=0
LOOP UNTIL K >= 0


print "K = " + string(K)
PRINT "K = "; STR$(K)
print "C = " + string(K - 273.15)
PRINT "C = "; STR$(K - 273.15)
print "F = " + string(K * 1.8 - 459.67)
PRINT "F = "; STR$(K * 1.8 - 459.67)
print "R = " + string(K * 1.8)
PRINT "R = "; STR$(K * 1.8)
END</syntaxhighlight>
</lang>


=={{header|BBC BASIC}}==
==={{header|XBasic}}===
{{works with|Windows XBasic}}
<lang bbcbasic>
<syntaxhighlight lang="qbasic">PROGRAM "Temperature conversion"
REPEAT
VERSION "0.001"
INPUT "Kelvin degrees (>=0): " K
UNTIL K>=0
@%=&20208
PRINT '"K = " K
PRINT "C = " K - 273.15
PRINT "F = " K * 1.8 - 459.67
PRINT "R = " K * 1.8
END
</lang>
{{out}}
<pre>
Kelvin degrees (>=0): 21


DECLARE FUNCTION Entry()
K = 21.00

C = -252.15
FUNCTION Entry()
F = -421.87
DO
R = 37.80
D$ = INLINE$("Kelvin degrees (>=0): ")
</pre>
K = SBYTE(D$)
LOOP UNTIL K >= 0

PRINT "K = " + STR$(K)
PRINT "C = " + STR$(K - 273.15)
PRINT "F = " + STR$(K * 1.8 - 459.67)
PRINT "R = " + STR$(K * 1.8)

END FUNCTION
END PROGRAM</syntaxhighlight>

==={{header|Yabasic}}===
<syntaxhighlight lang="yabasic">repeat
input "Kelvin degrees (>=0): " K
until K >= 0

print "K = " + str$(K)
print "C = " + str$(K - 273.15)
print "F = " + str$(K * 1.8 - 459.67)
print "R = " + str$(K * 1.8)
end</syntaxhighlight>

==={{header|ZX Spectrum Basic}}===
<syntaxhighlight lang="zxbasic">10 REM Translation of traditional basic version
20 INPUT "Kelvin Degrees? ";k
30 IF k <= 0 THEN STOP: REM A value of zero or less will end program
40 LET c = k - 273.15
50 LET f = k * 1.8 - 459.67
60 LET r = k * 1.8
70 PRINT k; " Kelvin is equivalent to"
80 PRINT c; " Degrees Celsius"
90 PRINT f; " Degrees Fahrenheit"
100 PRINT r; " Degrees Rankine"
110 GO TO 20</syntaxhighlight>


=={{header|Befunge}}==
=={{header|Befunge}}==
The temperature to convert is read from stdin. Befunge has no support for real numbers, though, so reading and writing of decimal values is done with character I/O. For the same reason, the temperature calculations use integer arithmetic to emulate fixed point. The first two lines handle the input; the second line performs the conversion calculations; and the last three handle the output.
The temperature to convert is read from stdin. Befunge has no support for real numbers, though, so reading and writing of decimal values is done with character I/O. For the same reason, the temperature calculations use integer arithmetic to emulate fixed point. The first two lines handle the input; the second line performs the conversion calculations; and the last three handle the output.


<lang befunge>0000>0p~>"."-:!#v_2-::0\`\9`+!#v_$1>/\:3`#v_\>\:3 \`#v_v
<syntaxhighlight lang="befunge">0000>0p~>"."-:!#v_2-::0\`\9`+!#v_$1>/\:3`#v_\>\:3 \`#v_v
1#<<^0 /2++g001!<1 \+g00\+*+55\< ^+55\-1< ^*+55\+1<v_
1#<<^0 /2++g001!<1 \+g00\+*+55\< ^+55\-1< ^*+55\+1<v_
"K"\-+**"!Y]"9:\"C"\--\**"^CIT"/5*9:\"F"\/5*9:\"R"\0\0<v
"K"\-+**"!Y]"9:\"C"\--\**"^CIT"/5*9:\"F"\/5*9:\"R"\0\0<v
v/+55\+*86%+55: /+55\+*86%+55: \0/+55+5*-\1*2 p00:`\0:,<
v/+55\+*86%+55: /+55\+*86%+55: \0/+55+5*-\1*2 p00:`\0:,<
>"."\>:55+% 68*v >:#,_$55+,\:!#@_^
>"."\>:55+% 68*v >:#,_$55+,\:!#@_^
$_^#!:/+55\+< ^\" :"_<g00*95 </lang>
$_^#!:/+55\+< ^\" :"_<g00*95 </syntaxhighlight>


{{out}}
{{out}}
Line 934: Line 1,162:


=={{header|Bracmat}}==
=={{header|Bracmat}}==
<lang bracmat>( ( rational2fixedpoint
<syntaxhighlight lang="bracmat">( ( rational2fixedpoint
= minus fixedpointnumber number decimals
= minus fixedpointnumber number decimals
. !arg:(#?number.~<0:~/#?decimals)
. !arg:(#?number.~<0:~/#?decimals)
Line 979: Line 1,207:
)
)
& done!
& done!
)</lang>
)</syntaxhighlight>
{{out}}
{{out}}
<pre>Enter Kelvin temperature:21.00
<pre>Enter Kelvin temperature:21.00
Line 989: Line 1,217:


=={{header|C}}==
=={{header|C}}==
<lang c>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <stdlib.h>


Line 1,017: Line 1,245:
}
}
return 0;
return 0;
}</lang>
}</syntaxhighlight>


=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
<lang csharp>using System;
<syntaxhighlight lang="csharp">using System;


namespace TemperatureConversion
namespace TemperatureConversion
Line 1,050: Line 1,278:
}
}
}
}
}</lang>
}</syntaxhighlight>


<pre>
<pre>
Line 1,061: Line 1,289:


=={{header|C++}}==
=={{header|C++}}==
<lang cpp>
<syntaxhighlight lang="cpp">
#include <iostream>
#include <iostream>
#include <iomanip>
#include <iomanip>
Line 1,116: Line 1,344:
}
}
//--------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,135: Line 1,363:


=={{header|Ceylon}}==
=={{header|Ceylon}}==
<lang ceylon>shared void run() {
<syntaxhighlight lang="ceylon">shared void run() {


void printKelvinConversions(Float kelvin) {
void printKelvinConversions(Float kelvin) {
Line 1,150: Line 1,378:
printKelvinConversions(21.0);
printKelvinConversions(21.0);
}</lang>
}</syntaxhighlight>


=={{header|Clojure}}==
=={{header|Clojure}}==
{{trans|Common Lisp}}
{{trans|Common Lisp}}
<lang clojure>(defn to-celsius [k]
<syntaxhighlight lang="clojure">(defn to-celsius [k]
(- k 273.15))
(- k 273.15))
(defn to-fahrenheit [k]
(defn to-fahrenheit [k]
Line 1,165: Line 1,393:
(format "Celsius: %.2f Fahrenheit: %.2f Rankine: %.2f"
(format "Celsius: %.2f Fahrenheit: %.2f Rankine: %.2f"
(to-celsius k) (to-fahrenheit k) (to-rankine k))
(to-celsius k) (to-fahrenheit k) (to-rankine k))
(format "Error: Non-numeric value entered.")))</lang>
(format "Error: Non-numeric value entered.")))</syntaxhighlight>


{{out}}
{{out}}
Line 1,174: Line 1,402:


=={{header|CLU}}==
=={{header|CLU}}==
<lang clu>kelvin = proc (k: real) returns (real)
<syntaxhighlight lang="clu">kelvin = proc (k: real) returns (real)
return(k)
return(k)
end kelvin
end kelvin
Line 1,211: Line 1,439:
stream$putl(po, f_form(c.func(k), 6, 2))
stream$putl(po, f_form(c.func(k), 6, 2))
end
end
end start_up</lang>
end start_up</syntaxhighlight>
{{out}}
{{out}}
<pre>Enter temperature in Kelvin: 21
<pre>Enter temperature in Kelvin: 21
Line 1,221: Line 1,449:
=={{header|COBOL}}==
=={{header|COBOL}}==
{{works with|Visual COBOL}}
{{works with|Visual COBOL}}
<lang cobol> IDENTIFICATION DIVISION.
<syntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
PROGRAM-ID. temp-conversion.
PROGRAM-ID. temp-conversion.
Line 1,256: Line 1,484:
GOBACK
GOBACK
.</lang>
.</syntaxhighlight>


{{out}}
{{out}}
Line 1,270: Line 1,498:
Three functions define the necessary conversion formulas. A fancy format string is used to print these values.
Three functions define the necessary conversion formulas. A fancy format string is used to print these values.


<lang lisp>
<syntaxhighlight lang="lisp">
(defun to-celsius (k)
(defun to-celsius (k)
(- k 273.15))
(- k 273.15))
Line 1,284: Line 1,512:
(to-celsius k) (to-fahrenheit k) (to-rankine k))
(to-celsius k) (to-fahrenheit k) (to-rankine k))
(format t "Error: Non-numeric value entered."))))
(format t "Error: Non-numeric value entered."))))
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 1,297: Line 1,525:


=={{header|D}}==
=={{header|D}}==
<lang d>double kelvinToCelsius(in double k) pure nothrow @safe {
<syntaxhighlight lang="d">double kelvinToCelsius(in double k) pure nothrow @safe {
return k - 273.15;
return k - 273.15;
}
}
Line 1,329: Line 1,557:
writefln("%2.2f K is below absolute zero", kelvin);
writefln("%2.2f K is below absolute zero", kelvin);
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,340: Line 1,568:
R 37.80
R 37.80
</pre>
</pre>

=={{header|Dart}}==
<syntaxhighlight lang="dart">double kelvinToCelsius(double k) {
return k - 273.15;
}

double kelvinToFahrenheit(double k) {
return k * 1.8 - 459.67;
}

double kelvinToRankine(double k) {
return k * 1.8;
}

void convertKelvin(double kelvin) {
print('K = ${kelvin.toStringAsFixed(2)}');
print('C = ${kelvinToCelsius(kelvin).toStringAsFixed(2)}');
print('F = ${kelvinToFahrenheit(kelvin).toStringAsFixed(2)}');
print('R = ${kelvinToRankine(kelvin).toStringAsFixed(2)}');
print('');
}

void main() {
convertKelvin(0.0);
convertKelvin(21.0);
}</syntaxhighlight>


=={{header|Delphi}}==
=={{header|Delphi}}==
<lang delphi>
<syntaxhighlight lang="delphi">
program Temperature;
program Temperature;


Line 1,384: Line 1,638:
readln;
readln;
end.
end.
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,395: Line 1,649:
=={{header|EasyLang}}==
=={{header|EasyLang}}==


<lang>k = number input
<syntaxhighlight lang="text">k = number input
print k & " °K"
print k & " °K"
print k - 273.15 & " °C"
print k - 273.15 & " °C"
print k * 1.8 - 459.67 & " °F"
print k * 1.8 - 459.67 & " °F"
print k * 1.8 & " °R"</lang>
print k * 1.8 & " °R"</syntaxhighlight>


=={{header|Elena}}==
=={{header|Elena}}==
ELENA 4.1 :
ELENA 4.1 :
<lang elena>import extensions;
<syntaxhighlight lang="elena">import extensions;
convertKelvinToFahrenheit(x)
convertKelvinToFahrenheit(x)
Line 1,435: Line 1,689:
console.printLine("Celsius: ", convertKelvinToCelsius(kelvinTemp));
console.printLine("Celsius: ", convertKelvinToCelsius(kelvinTemp));
console.readChar()
console.readChar()
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,446: Line 1,700:


=={{header|Elixir}}==
=={{header|Elixir}}==
<lang elixir>defmodule Temperature do
<syntaxhighlight lang="elixir">defmodule Temperature do
def conversion(t) do
def conversion(t) do
IO.puts "K : #{f(t)}"
IO.puts "K : #{f(t)}"
Line 1,461: Line 1,715:
end
end


Temperature.task</lang>
Temperature.task</syntaxhighlight>


{{out}}
{{out}}
Line 1,475: Line 1,729:


=={{header|Erlang}}==
=={{header|Erlang}}==
<lang erlang>% Implemented by Arjun Sunel
<syntaxhighlight lang="erlang">% Implemented by Arjun Sunel
-module(temp_conv).
-module(temp_conv).
-export([main/0]).
-export([main/0]).
Line 1,490: Line 1,744:
f(A) ->
f(A) ->
(round(A*100))/100 .
(round(A*100))/100 .
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,505: Line 1,759:


=={{header|Euphoria}}==
=={{header|Euphoria}}==
<syntaxhighlight lang="openeuphoria">
<lang OpenEuphoria>
include std/console.e
include std/console.e


Line 1,513: Line 1,767:
printf(1,"K = %5.2f\nC = %5.2f\nF = %5.2f\nR = %5.2f\n\n",{K,K-273.15,K*1.8-459.67,K*1.8})
printf(1,"K = %5.2f\nC = %5.2f\nF = %5.2f\nR = %5.2f\n\n",{K,K-273.15,K*1.8-459.67,K*1.8})
end while
end while
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,526: Line 1,780:


=={{header|Excel}}==
=={{header|Excel}}==
<lang>A1 : Kelvin
<syntaxhighlight lang="text">A1 : Kelvin
B1 : Celsius
B1 : Celsius
C1 : Fahrenheit
C1 : Fahrenheit
Line 1,534: Line 1,788:
C2 : =K*1.8-459.67
C2 : =K*1.8-459.67
D2 : =K*1.8
D2 : =K*1.8
Input in A1 </lang>
Input in A1 </syntaxhighlight>
{{Out}}
{{Out}}
<pre>
<pre>
Line 1,551: Line 1,805:


{{Works with|Office 365 betas 2021}}
{{Works with|Office 365 betas 2021}}
<lang lisp>FROMKELVIN
<syntaxhighlight lang="lisp">FROMKELVIN
=LAMBDA(toUnit,
=LAMBDA(toUnit,
LAMBDA(n,
LAMBDA(n,
Line 1,566: Line 1,820:
)
)
)
)
)</lang>
)</syntaxhighlight>


The example below generates the spaced list of test values on the left from the expression ENUMFROMTHENTO(240)(250)(390),
The example below generates the spaced list of test values on the left from the expression ENUMFROMTHENTO(240)(250)(390),
applying the following custom function:
applying the following custom function:
<lang lisp>ENUMFROMTHENTO
<syntaxhighlight lang="lisp">ENUMFROMTHENTO
=LAMBDA(a,
=LAMBDA(a,
LAMBDA(b,
LAMBDA(b,
Line 1,584: Line 1,838:
)
)
)
)
)</lang>
)</syntaxhighlight>


The four columns on the right of the output read their target format from the label cell at the top of each column.
The four columns on the right of the output read their target format from the label cell at the top of each column.
Line 1,723: Line 1,977:


=={{header|Ezhil}}==
=={{header|Ezhil}}==
<syntaxhighlight lang="ezhil">
<lang Ezhil>
# convert from Kelvin
# convert from Kelvin
நிரல்பாகம் கெல்வின்_இருந்து_மாற்று( k )
நிரல்பாகம் கெல்வின்_இருந்து_மாற்று( k )
Line 1,732: Line 1,986:
கெல்வின்_இருந்து_மாற்று( 273 ) #freezing pt of water
கெல்வின்_இருந்து_மாற்று( 273 ) #freezing pt of water
கெல்வின்_இருந்து_மாற்று( 30 + 273 ) #room temperature in Summer
கெல்வின்_இருந்து_மாற்று( 30 + 273 ) #room temperature in Summer
</syntaxhighlight>
</lang>


=={{header|F_Sharp|F#}}==
=={{header|F_Sharp|F#}}==
<lang fsharp>
<syntaxhighlight lang="fsharp">
// Define units of measure
// Define units of measure
[<Measure>] type k
[<Measure>] type k
Line 1,752: Line 2,006:
printfn "%A Kelvin is %A Fahrenheit" K (kelvinToFahrenheit K)
printfn "%A Kelvin is %A Fahrenheit" K (kelvinToFahrenheit K)
printfn "%A Kelvin is %A Rankine" K (kelvinToRankine K)
printfn "%A Kelvin is %A Rankine" K (kelvinToRankine K)
</syntaxhighlight>
</lang>


=={{header|Factor}}==
=={{header|Factor}}==
<lang>USING: combinators formatting kernel math ;
<syntaxhighlight lang="text">USING: combinators formatting kernel math ;
IN: rosetta-code.temperature
IN: rosetta-code.temperature


Line 1,766: Line 2,020:
"K %.2f\nC %.2f\nF %.2f\nR %.2f\n" printf ;
"K %.2f\nC %.2f\nF %.2f\nR %.2f\n" printf ;
21 convert</lang>
21 convert</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,776: Line 2,030:


=={{header|FOCAL}}==
=={{header|FOCAL}}==
<lang focal>01.10 ASK "TEMPERATURE IN KELVIN", K
<syntaxhighlight lang="focal">01.10 ASK "TEMPERATURE IN KELVIN", K
01.20 TYPE "K ", %6.02, K, !
01.20 TYPE "K ", %6.02, K, !
01.30 TYPE "C ", %6.02, K - 273.15, !
01.30 TYPE "C ", %6.02, K - 273.15, !
01.40 TYPE "F ", %6.02, K * 1.8 - 459.67, !
01.40 TYPE "F ", %6.02, K * 1.8 - 459.67, !
01.50 TYPE "R ", %6.02, K * 1.8, !</lang>
01.50 TYPE "R ", %6.02, K * 1.8, !</syntaxhighlight>
{{out}}
{{out}}
<pre>TEMPERATURE IN KELVIN:373.15
<pre>TEMPERATURE IN KELVIN:373.15
Line 1,790: Line 2,044:
=={{header|Forth}}==
=={{header|Forth}}==
{{works with|GNU Forth}} for the command line handling
{{works with|GNU Forth}} for the command line handling
<lang forth>: k>°C ( F: kelvin -- celsius ) 273.15e0 f- ;
<syntaxhighlight lang="forth">: k>°C ( F: kelvin -- celsius ) 273.15e0 f- ;
: k>°R ( F: kelvin -- rankine ) 1.8e0 f* ;
: k>°R ( F: kelvin -- rankine ) 1.8e0 f* ;
: °R>°F ( F: rankine -- fahrenheit ) 459.67e0 f- ;
: °R>°F ( F: rankine -- fahrenheit ) 459.67e0 f- ;
Line 1,802: Line 2,056:
then ;
then ;


main bye</lang>
main bye</syntaxhighlight>
{{out}}
{{out}}
<pre>&gt; gforthamd64 rosetta_temp_conv.fs 21
<pre>&gt; gforthamd64 rosetta_temp_conv.fs 21
Line 1,812: Line 2,066:
=={{header|Fortran}}==
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
{{works with|Fortran|90 and later}}
<lang fortran>Program Temperature
<syntaxhighlight lang="fortran">Program Temperature
implicit none
implicit none
Line 1,837: Line 2,091:


end subroutine
end subroutine
end program</lang>
end program</syntaxhighlight>

=={{header|FreeBASIC}}==
<lang freebasic>' FB 1.05.0 Win64

Sub convKelvin(temp As Double)
Dim f As String = "####.##"
Print Using f; temp;
Print " degrees Kelvin"
Print Using f; temp - 273.15;
Print " degrees Celsius"
Print Using f; (temp - 273.15) * 1.8 + 32.0;
Print " degrees Fahreneit"
Print Using f; (temp - 273.15) * 1.8 + 32.0 + 459.67;
Print " degrees Rankine"
End Sub

convKelvin(0.0)
Print
convKelvin(21.0)
Print
Print "Press any key to quit"
Sleep</lang>

{{out}}
<pre>
0.00 degrees Kelvin
-273.15 degrees Celsius
-459.67 degrees Fahreneit
0.00 degrees Rankine

21.00 degrees Kelvin
-252.15 degrees Celsius
-421.87 degrees Fahreneit
37.80 degrees Rankine
</pre>

=={{header|Gambas}}==
<lang gambas>Public Sub Form_Open()
Dim fKelvin As Float

fKelvin = InputBox("Enter a Kelvin value", "Kelvin converter")

Print "Kelvin =\t" & Format(Str(fKelvin), "#.00")
Print "Celsius =\t" & Format(Str(fKelvin - 273.15), "#.00")
Print "Fahrenheit =\t" & Format(Str(fKelvin * 1.8 - 459.67), "#.00")
Print "Rankine =\t" & Format(Str(fKelvin * 1.8), "#.00")

End</lang>
Output:
<pre>
Kelvin = 21.00
Celsius = -252.15
Fahrenheit = -421.87
Rankine = 37.80
</pre>


=={{header|Go}}==
=={{header|Go}}==
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 1,921: Line 2,120:
fmt.Printf("F %.2f\n", k*9/5-459.67)
fmt.Printf("F %.2f\n", k*9/5-459.67)
fmt.Printf("R %.2f\n", k*9/5)
fmt.Printf("R %.2f\n", k*9/5)
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,932: Line 2,131:


=={{header|Groovy}}==
=={{header|Groovy}}==
<syntaxhighlight lang="groovy">
<lang Groovy>
class Convert{
class Convert{
static void main(String[] args){
static void main(String[] args){
Line 1,945: Line 2,144:
static def k_to_r(def k=21.0){return k*1.8;}
static def k_to_r(def k=21.0){return k*1.8;}
}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,956: Line 2,155:
=={{header|Haskell}}==
=={{header|Haskell}}==


<lang haskell>import System.Exit (die)
<syntaxhighlight lang="haskell">import System.Exit (die)
import Control.Monad (mapM_)
import Control.Monad (mapM_)


Line 1,971: Line 2,170:
where labels = ["kelvin: ", "celcius: ", "farenheit: ", "rankine: "]
where labels = ["kelvin: ", "celcius: ", "farenheit: ", "rankine: "]
conversions = [id, subtract 273, subtract 459.67 . (1.8 *), (*1.8)]
conversions = [id, subtract 273, subtract 459.67 . (1.8 *), (*1.8)]
nums = (show . ($n)) <$> conversions</lang>
nums = (show . ($n)) <$> conversions</syntaxhighlight>


Or with properly managed exceptions:
Or with properly managed exceptions:


<lang haskell>{-# LANGUAGE LambdaCase #-}
<syntaxhighlight lang="haskell">{-# LANGUAGE LambdaCase #-}


import System.Exit (die)
import System.Exit (die)
Line 1,998: Line 2,197:
t <- liftIO getLine >>= tryRead "Could not read temp"
t <- liftIO getLine >>= tryRead "Could not read temp"
tryAssert "Temp cannot be negative" (t>=0)
tryAssert "Temp cannot be negative" (t>=0)
return t</lang>
return t</syntaxhighlight>


=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==


The following program works in both languages:
The following program works in both languages:
<lang unicon>procedure main(A)
<syntaxhighlight lang="unicon">procedure main(A)
k := A[1] | 21.00
k := A[1] | 21.00
write("K ",k)
write("K ",k)
Line 2,009: Line 2,208:
write("R ",r := k*(9.0/5.0))
write("R ",r := k*(9.0/5.0))
write("F ",r - 459.67)
write("F ",r - 459.67)
end</lang>
end</syntaxhighlight>


Sample runs:
Sample runs:
Line 2,026: Line 2,225:
->
->
</pre>
</pre>

=={{header|Insitux}}==
<syntaxhighlight lang="insitux">(var K->C (+ -273.15))
(var K->R (* 1.8))
(var K->F (comp K->R (+ -459.67)))

(function kelvin-conversions K
(let [C R F] ((juxt K->C K->R K->F) K)
[C R F] (map @(round 2) [C R F]))
(print K " K / " C " °C / " R " °R / " F " °F"))

(kelvin-conversions 21.0)
;prints "21 K / -252.15 °C / 37.8 °R / -421.87 °F"</syntaxhighlight>


=={{header|J}}==
=={{header|J}}==
'''Solution''':<lang j> NB. Temp conversions are all linear polynomials
'''Solution''':<syntaxhighlight lang="j"> NB. Temp conversions are all linear polynomials
K2K =: 0 1 NB. K = (1 *k) + 0
K2K =: 0 1 NB. K = (1 *k) + 0
K2C =: _273 1 NB. C = (1 *k) - 273
K2C =: _273 1 NB. C = (1 *k) - 273
Line 2,038: Line 2,250:
NB. numeric matrix J programs would manipulate
NB. numeric matrix J programs would manipulate
NB. directly.
NB. directly.
k2KCFR =: (K2K , K2C , K2F ,: K2R) p./ ]</lang>
k2KCFR =: (K2K , K2C , K2F ,: K2R) p./ ]</syntaxhighlight>
{{out|Example}}
{{out|Example}}
<lang j> NB. Format matrix for printing & tag each
<syntaxhighlight lang="j"> NB. Format matrix for printing & tag each
NB. temp with scale, for human legibility
NB. temp with scale, for human legibility
fmt =: [: (;:inv"1) 0 _1 |: 'KCFR' ;"0 1"_1 '0.2' 8!:0 ]
fmt =: [: (;:inv"1) 0 _1 |: 'KCFR' ;"0 1"_1 '0.2' 8!:0 ]
Line 2,061: Line 2,273:
C -252.00 -173.00 27.00
C -252.00 -173.00 27.00
F -421.87 -279.67 80.33
F -421.87 -279.67 80.33
R 37.80 180.00 540.00</lang>
R 37.80 180.00 540.00</syntaxhighlight>
'''Notes''': The approach is founded on polynomials, one for each conversion (e.g. <tt>Fahrenheit = 1.8*x - 459.67</tt> where <tt>x</tt> is measured in degrees Kelvin), and all polynomials are evaluated simultaneously using the built-in <code>p.</code>. Through some code decorations (specifically the <code>/</code> in <code>p./</code> the <code>"0 1"_1</code> and the <code>0 _1 |:</code>), we permit our function to convert arrays of temperatures of arbitrarily high dimension (a single temp, lists of temps, tables of temps, cubes of temps, etc).
'''Notes''': The approach is founded on polynomials, one for each conversion (e.g. <tt>Fahrenheit = 1.8*x - 459.67</tt> where <tt>x</tt> is measured in degrees Kelvin), and all polynomials are evaluated simultaneously using the built-in <code>p.</code>. Through some code decorations (specifically the <code>/</code> in <code>p./</code> the <code>"0 1"_1</code> and the <code>0 _1 |:</code>), we permit our function to convert arrays of temperatures of arbitrarily high dimension (a single temp, lists of temps, tables of temps, cubes of temps, etc).


=={{header|Java}}==
=={{header|Java}}==
<lang java>public class TemperatureConversion {
<syntaxhighlight lang="java">public class TemperatureConversion {
public static void main(String args[]) {
public static void main(String args[]) {
if (args.length == 1) {
if (args.length == 1) {
Line 2,095: Line 2,307:
return k * 1.8;
return k * 1.8;
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,110: Line 2,322:


===ES5===
===ES5===
<lang javascript>var k2c = k => k - 273.15
<syntaxhighlight lang="javascript">var k2c = k => k - 273.15
var k2r = k => k * 1.8
var k2r = k => k * 1.8
var k2f = k => k2r(k) - 459.67
var k2f = k => k2r(k) - 459.67
Line 2,123: Line 2,335:
kCnv(21)
kCnv(21)
kCnv(295)</lang>
kCnv(295)</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,134: Line 2,346:
Deriving '''kelvinTranslations()''' from a more general '''heatBabel()''' function.
Deriving '''kelvinTranslations()''' from a more general '''heatBabel()''' function.


<lang javascript>(() => {
<syntaxhighlight lang="javascript">(() => {
'use strict';
'use strict';


Line 2,172: Line 2,384:


})();
})();
</syntaxhighlight>
</lang>


{{Out}}
{{Out}}
Line 2,182: Line 2,394:


=={{header|jq}}==
=={{header|jq}}==
The hard part here is defining round/1 generically.<lang jq>
The hard part here is defining round/1 generically.<syntaxhighlight lang="jq">
# round(keep) takes as input any jq (i.e. JSON) number and emits a string.
# round(keep) takes as input any jq (i.e. JSON) number and emits a string.
# "keep" is the desired maximum number of numerals after the decimal point,
# "keep" is the desired maximum number of numerals after the decimal point,
Line 2,219: Line 2,431:
end;
end;


cfr</lang>
cfr</syntaxhighlight>
'''Example'''
'''Example'''
<lang sh> $ jq -M -r -f Temperature_conversion.jq
<syntaxhighlight lang="sh"> $ jq -M -r -f Temperature_conversion.jq
21
21
Kelvin: 21
Kelvin: 21
Line 2,229: Line 2,441:
-1
-1
jq: error: cfr: -1 is an invalid temperature in degrees Kelvin</lang>
jq: error: cfr: -1 is an invalid temperature in degrees Kelvin</syntaxhighlight>


=={{header|Julia}}==
=={{header|Julia}}==
<lang julia>cfr(k) = print("Kelvin: $k, ",
<syntaxhighlight lang="julia">cfr(k) = print("Kelvin: $k, ",
"Celsius: $(round(k-273.15,2)), ",
"Celsius: $(round(k-273.15,2)), ",
"Fahrenheit: $(round(k*1.8-459.67,2)), ",
"Fahrenheit: $(round(k*1.8-459.67,2)), ",
"Rankine: $(round(k*1.8,2))")</lang>
"Rankine: $(round(k*1.8,2))")</syntaxhighlight>
<pre>julia> cfr(21)
<pre>julia> cfr(21)
Kelvin: 21, Celsius: -252.15, Fahrenheit: -421.87, Rankine: 37.8</pre>
Kelvin: 21, Celsius: -252.15, Fahrenheit: -421.87, Rankine: 37.8</pre>


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>// version 1.1.2
<syntaxhighlight lang="scala">// version 1.1.2


class Kelvin(val degrees: Double) {
class Kelvin(val degrees: Double) {
Line 2,260: Line 2,472:
println("F ${f.format(k.toFahreneit())}\n")
println("F ${f.format(k.toFahreneit())}\n")
println("R ${f.format(k.toRankine())}")
println("R ${f.format(k.toRankine())}")
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 2,276: Line 2,488:


=={{header|Lambdatalk}}==
=={{header|Lambdatalk}}==
<lang scheme>
<syntaxhighlight lang="scheme">
{def to-celsius {lambda {:k} {- :k 273.15}}}
{def to-celsius {lambda {:k} {- :k 273.15}}}
-> to-celsius
-> to-celsius
Line 2,303: Line 2,515:
-421.87 farenheit
-421.87 farenheit
37.8 rankine
37.8 rankine
</syntaxhighlight>
</lang>


=={{header|Lasso}}==
=={{header|Lasso}}==
<lang Lasso>define tempconverter(temp, kind) => {
<syntaxhighlight lang="lasso">define tempconverter(temp, kind) => {


local(
local(
Line 2,356: Line 2,568:
tempconverter(37.80, 'r')
tempconverter(37.80, 'r')
'<br />'
'<br />'
tempconverter(69.80, 'f')</lang>
tempconverter(69.80, 'f')</syntaxhighlight>
<pre>K = 21.00 C = -252.15 R = 37.80 F = -421.87
<pre>K = 21.00 C = -252.15 R = 37.80 F = -421.87
K = 294.15 C = 21.00 R = 529.47 F = 69.80
K = 294.15 C = 21.00 R = 529.47 F = 69.80
Line 2,364: Line 2,576:


=={{header|LIL}}==
=={{header|LIL}}==
<lang tcl># Temperature conversion, in LIL
<syntaxhighlight lang="tcl"># Temperature conversion, in LIL
func kToc k {expr $k - 273.15}
func kToc k {expr $k - 273.15}
func kTor k {expr $k / 5.0 * 9.0}
func kTor k {expr $k / 5.0 * 9.0}
Line 2,375: Line 2,587:
print "Fahrenheit: [kTof $k]"
print "Fahrenheit: [kTof $k]"
print "Rankine: [kTor $k]"
print "Rankine: [kTor $k]"
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 2,386: Line 2,598:


=={{header|LiveCode}}==
=={{header|LiveCode}}==
<lang LiveCode>function convertDegrees k
<syntaxhighlight lang="livecode">function convertDegrees k
put k/5 * 9 into r
put k/5 * 9 into r
put k - 273.15 into c
put k - 273.15 into c
put r - 459.67 into f
put r - 459.67 into f
return k,r,c,f
return k,r,c,f
end convertDegrees</lang>
end convertDegrees</syntaxhighlight>
Example<lang LiveCode>put convertDegrees(21.00) into tTemp
Example<syntaxhighlight lang="livecode">put convertDegrees(21.00) into tTemp
put item 1 of tTemp into temperature["Kelvin"]
put item 1 of tTemp into temperature["Kelvin"]
put item 2 of tTemp into temperature["Rankine"]
put item 2 of tTemp into temperature["Rankine"]
Line 2,400: Line 2,612:
put temperature
put temperature


-- Celsius:-252.15,Fahrenheit:-421.87,Kelvin:21.00,Rankine:37.8</lang>
-- Celsius:-252.15,Fahrenheit:-421.87,Kelvin:21.00,Rankine:37.8</syntaxhighlight>


=={{header|Lua}}==
=={{header|Lua}}==


<lang lua>function convert_temp(k)
<syntaxhighlight lang="lua">function convert_temp(k)
local c = k - 273.15
local c = k - 273.15
local r = k * 1.8
local r = k * 1.8
Line 2,416: Line 2,628:
Rankine: %.2f °R
Rankine: %.2f °R
Fahrenheit: %.2f °F
Fahrenheit: %.2f °F
]],convert_temp(21.0)))</lang>
]],convert_temp(21.0)))</syntaxhighlight>

=={{header|Liberty BASIC}}==

<lang Liberty BASIC>Do
Input "Kelvin degrees (>=0): ";K
Loop Until (K >= 0)

Print "K = ";K
Print "C = ";(K - 273.15)
Print "F = ";(K * 1.8 - 459.67)
Print "R = ";(K * 1.8)
End</lang>

{{out}}
<pre>Kelvin degrees (>=0): 21
K = 21
C = -252.15
F = -421.87
R = 37.8
</pre>


=={{header|Maple}}==
=={{header|Maple}}==
<lang maple>tempConvert := proc(k)
<syntaxhighlight lang="maple">tempConvert := proc(k)
seq(printf("%c: %.2f\n", StringTools[UpperCase](substring(i, 1)), convert(k, temperature, kelvin, i)), i in [kelvin, Celsius, Fahrenheit, Rankine]);
seq(printf("%c: %.2f\n", StringTools[UpperCase](substring(i, 1)), convert(k, temperature, kelvin, i)), i in [kelvin, Celsius, Fahrenheit, Rankine]);
return NULL;
return NULL;
end proc:
end proc:


tempConvert(21);</lang>
tempConvert(21);</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,454: Line 2,646:


=={{header|Mathematica}}/{{header|Wolfram Language}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<lang Mathematica>tempConvert[t_] := # -> Thread@UnitConvert[#,{"DegreesFahrenheit", "DegreesCelsius", "DegreesRankine"}]&@Quantity[N@t, "Kelvins"]
<syntaxhighlight lang="mathematica">tempConvert[t_] := # -> Thread@UnitConvert[#,{"DegreesFahrenheit", "DegreesCelsius", "DegreesRankine"}]&@Quantity[N@t, "Kelvins"]
tempConvert[21]</lang>
tempConvert[21]</syntaxhighlight>
{{out}}
{{out}}
<pre>21.K -> {-421.87°F,-252.15°C,37.8°R}</pre>
<pre>21.K -> {-421.87°F,-252.15°C,37.8°R}</pre>
Line 2,461: Line 2,653:
=={{header|min}}==
=={{header|min}}==
{{works with|min|0.19.3}}
{{works with|min|0.19.3}}
<lang min>(
<syntaxhighlight lang="min">(
((float) (273.15 -) (9 5 / * 459.67 -) (9 5 / *)) cleave
((float) (273.15 -) (9 5 / * 459.67 -) (9 5 / *)) cleave
() 'cons 4 times "K $1\nC $2\nF $3\nR $4" swap % puts!
() 'cons 4 times "K $1\nC $2\nF $3\nR $4" swap % puts!
) :convert
) :convert


21 convert</lang>
21 convert</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,476: Line 2,668:


=={{header|MiniScript}}==
=={{header|MiniScript}}==
<lang MiniScript>fromKelvin = function(temp)
<syntaxhighlight lang="miniscript">fromKelvin = function(temp)
print temp + " degrees in Kelvin is:"
print temp + " degrees in Kelvin is:"
Celsius = temp - 273.15
Celsius = temp - 273.15
Line 2,487: Line 2,679:


temp = input("Enter a temperature in Kelvin: ")
temp = input("Enter a temperature in Kelvin: ")
fromKelvin temp.val</lang>
fromKelvin temp.val</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,504: Line 2,696:


=={{header|MiniZinc}}==
=={{header|MiniZinc}}==
<lang MiniZinc>float: kelvin;
<syntaxhighlight lang="minizinc">float: kelvin;


var float: celsius;
var float: celsius;
Line 2,515: Line 2,707:
solve satisfy;
solve satisfy;


output ["K \(kelvin)\n", "C \(celsius)\n", "F \(fahrenheit)\n", "R \(rankine)\n"];</lang>
output ["K \(kelvin)\n", "C \(celsius)\n", "F \(fahrenheit)\n", "R \(rankine)\n"];</syntaxhighlight>
{{out}}<pre>
{{out}}<pre>
Compiling temperature.mzn, additional arguments kelvin=1000;
Compiling temperature.mzn, additional arguments kelvin=1000;
Line 2,528: Line 2,720:


=={{header|МК-61/52}}==
=={{header|МК-61/52}}==
<lang mk61>П7 0 , 8 * П8 ИП7 9 * 5
<syntaxhighlight lang="mk61">П7 0 , 8 * П8 ИП7 9 * 5
/ 3 2 + П9 ИП7 2 7 3 ,
/ 3 2 + П9 ИП7 2 7 3 ,
1 5 + П4 С/П П8 1 , 8 /
1 5 + П4 С/П П8 1 , 8 /
БП 00 П9 3 2 - 5 * 9 /
БП 00 П9 3 2 - 5 * 9 /
БП 00 П4 2 7 3 , 1 5 -
БП 00 П4 2 7 3 , 1 5 -
БП 00</lang>
БП 00</syntaxhighlight>


''Instruction:''
''Instruction:''
Line 2,558: Line 2,750:
==={{header|mLite}}===
==={{header|mLite}}===
Temperature in Kelvin given on command line.
Temperature in Kelvin given on command line.
<lang ocaml>fun KtoC n = n - 273.15;
<syntaxhighlight lang="ocaml">fun KtoC n = n - 273.15;
fun KtoF n = n * 1.8 - 459.67;
fun KtoF n = n * 1.8 - 459.67;
fun KtoR n = n * 1.8;
fun KtoR n = n * 1.8;
Line 2,574: Line 2,766:
print "Rankine: "; println ` KtoR K
print "Rankine: "; println ` KtoR K
end
end
</syntaxhighlight>
</lang>


=={{header|Nanoquery}}==
=={{header|Nanoquery}}==
{{trans|Python}}
{{trans|Python}}
<lang Nanoquery>% while true
<syntaxhighlight lang="nanoquery">% while true
... print "K ? "
... print "K ? "
... k = float(input())
... k = float(input())
Line 2,588: Line 2,780:
K ? 222.2
K ? 222.2
222.200 Kelvin = -50.9500 Celsius = -59.7100 Fahrenheit = 399.960 Rankine degrees.
222.200 Kelvin = -50.9500 Celsius = -59.7100 Fahrenheit = 399.960 Rankine degrees.
K ? </lang>
K ? </syntaxhighlight>


=={{header|NetRexx}}==
=={{header|NetRexx}}==
<lang NetRexx>/* NetRexx */
<syntaxhighlight lang="netrexx">/* NetRexx */
options replace format comments java crossref symbols
options replace format comments java crossref symbols


Line 2,776: Line 2,968:


return
return
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre pre style="height: 40ex; overflow: scroll">
<pre pre style="height: 40ex; overflow: scroll">
Line 2,841: Line 3,033:


=={{header|Never}}==
=={{header|Never}}==
<syntaxhighlight lang="never">
<lang Never>
func KtoC(k : float) -> float { k - 273.15 }
func KtoC(k : float) -> float { k - 273.15 }
func KtoF(k : float) -> float { k * 1.8 - 459.67 }
func KtoF(k : float) -> float { k * 1.8 - 459.67 }
Line 2,858: Line 3,050:
0
0
}
}
</syntaxhighlight>
</lang>
{{output}}
{{output}}
<pre>
<pre>
Line 2,868: Line 3,060:


=={{header|NewLISP}}==
=={{header|NewLISP}}==
<syntaxhighlight lang="newlisp">
<lang NewLISP>
(define (to-celsius k)
(define (to-celsius k)
(- k 273.15)
(- k 273.15)
Line 2,890: Line 3,082:
)
)
)
)
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,901: Line 3,093:
=={{header|Nim}}==
=={{header|Nim}}==
{{libheader|strfmt}}
{{libheader|strfmt}}
<lang nim>import rdstdin, strutils, strfmt
<syntaxhighlight lang="nim">import rdstdin, strutils, strfmt


while true:
while true:
let k = parseFloat readLineFromStdin "K ? "
let k = parseFloat readLineFromStdin "K ? "
echo "{:g} Kelvin = {:g} Celsius = {:g} Fahrenheit = {:g} Rankine degrees".fmt(
echo "{:g} Kelvin = {:g} Celsius = {:g} Fahrenheit = {:g} Rankine degrees".fmt(
k, k - 273.15, k * 1.8 - 459.67, k * 1.8)</lang>
k, k - 273.15, k * 1.8 - 459.67, k * 1.8)</syntaxhighlight>
Sample usage:
Sample usage:
<pre>K ? 21.0
<pre>K ? 21.0
Line 2,914: Line 3,106:


=={{header|Objeck}}==
=={{header|Objeck}}==
<lang objeck>
<syntaxhighlight lang="objeck">
class Temperature {
class Temperature {
function : Main(args : String[]) ~ Nil {
function : Main(args : String[]) ~ Nil {
Line 2,940: Line 3,132:
}
}
}
}
</syntaxhighlight>
</lang>


<pre>
<pre>
Line 2,950: Line 3,142:


=={{header|Objective-C}}==
=={{header|Objective-C}}==
<lang objc>#import <Foundation/Foundation.h>
<syntaxhighlight lang="objc">#import <Foundation/Foundation.h>


int main(int argc, const char * argv[])
int main(int argc, const char * argv[])
Line 2,968: Line 3,160:
}
}
return 0;
return 0;
}</lang>
}</syntaxhighlight>


=={{header|OCaml}}==
=={{header|OCaml}}==
<lang ocaml>
<syntaxhighlight lang="ocaml">
let print_temp s t =
let print_temp s t =
print_string s;
print_string s;
Line 2,992: Line 3,184:
print_temp "F " (kelvin_to_fahrenheit k);
print_temp "F " (kelvin_to_fahrenheit k);
print_temp "R " (kelvin_to_rankine k);;
print_temp "R " (kelvin_to_rankine k);;
</syntaxhighlight>
</lang>


Sample session:
Sample session:
Line 3,005: Line 3,197:


=={{header|Oforth}}==
=={{header|Oforth}}==
<syntaxhighlight lang="oforth">: kelvinToCelsius 273.15 - ;

<lang Oforth>: kelvinToCelsius 273.15 - ;
: kelvinToFahrenheit 1.8 * 459.67 - ;
: kelvinToFahrenheit 1.8 * 459.67 - ;
: kelvinToRankine 1.8 * ;
: kelvinToRankine 1.8 * ;
Line 3,013: Line 3,204:
n kelvinToCelsius println
n kelvinToCelsius println
n kelvinToFahrenheit println
n kelvinToFahrenheit println
n kelvinToRankine println ;</lang>
n kelvinToRankine println ;</syntaxhighlight>


{{out}}
{{out}}
Line 3,021: Line 3,212:
-421.87
-421.87
37.8
37.8
</pre>

=={{header|ooRexx}}==
{{trans|REXX}}
<syntaxhighlight lang="ooRexx">
/* REXX convert temperatures from/to 58 temperature scakes */
Parse Source src
Parse Var src . how .

If how='FUNCTION' Then
If arg(2)='' Then
tlist=arg(1) 'TO' 'K'
Else
tlist=arg(1) 'TO' arg(2)
Else Do
Parse Arg tList /* get the list of pairs */
If arg(1)='?' Then Call help
tList= space(tList) /* elide any and all superfluous blanks.*/
End
Do While tList>'' /* process the list */
Parse Var tList pair ',' tList /* pairs are separated by commas */
Parse Var pair from_to '(' desc /* get spec and description (If any) */
Parse upper Var from_to fromt ' TO' toscal . /* get temperature and target scale */
If toscal=='' Then Do /* no target scale: show all targets */
If how='FUNCTION' Then Do
all=0
toscal='K'
End
Else Do
all=1
toscale='all'
End
End
Else Do
all=0
toscale=scalename(toscal)
End

Parse Var fromt fromtemp fromscal
If fromscal='' Then
fromscale='K' /*assume kelvin as per task requirement*/
Else
fromscale=scalename(fromscal)

If fromt='' Then Call serr 'No source temperature specified'
If \datatype(fromtemp,'N') Then Call serr 'Source temperature ('fromtemp') not numeric'
If left(fromscale,1)='*' Then Call serr 'Invalid source scale' fromscale
If left(toscale,1)='*' Then Call serr 'Invalid target scale' toscale

F=convert2Fahrenheit(fromtemp fromscale) /*convert a temperature --? Fahrenheit.*/

If F<-459.67 Then Call serr 'Source temperature below absolute zero'

If how<>'FUNCTION' Then Do /* write a header line */
If desc<>'' Then desc='('desc
Say pair /*show original value & scale (for sep)*/
If toscale<>'' Then
Say fromtemp fromscale 'TO' toscale
Else
Say fromtemp fromscale 'TO' all
End

Call convert2specific

End /* while tlist>'' */
Exit /* stick a fork in it, we're all done. */

scaleName:
Parse Arg sn /* abbreviations --> temp. short name. */
snU=translate(sn) /* uppercase version of temperature unit*/
snU=translate(snU,'-eE',"_éÉ") /* translate some accented characters. */

If left(snU,7)=='DEGREES' Then /* is this a redundant "degrees" ? */
snU=substr(snU,8)
If left(snU,6)=='DEGREE' Then /* " " " " "degree" ? */
snU=substr(snU,7)
snU=strip(snU) /* elide all leading & trailing blanks */
_= length(snU) /* obtain the length of the snU value */

If right(snU,1)=='S' & _>1 Then
snU=left(snU,_-1) /* remove any trailing plural(s) */

Select /* get scalename from abbrevuation */
When abbrev('ALL' , snU, 3) Then sn= "ALL"
When abbrev('ABSOLUTE' , snU, 1) Then sn= "ABSOLUTE"
When abbrev('AMONTON' , snU) Then sn= "AMONTON"
When abbrev('BARNDORF' , snU,2) |,
abbrev('BARNSDORF' , snU,2) Then sn= "BARNSDORF"
When abbrev('BEAUMIUR' , snU,3) |,
abbrev('BEAUMUIR' , snU,3) Then sn= "BEAUMUIR"
When abbrev('BENERT' , snU,3) |,
abbrev('BENART' , snU,3) Then sn= "BENART"
When abbrev('BRISSEN' , snU,3) |,
abbrev('BRISSON' , snU,3) Then sn= "BRISSEN"
When abbrev('BURGEN' , snU,3) |,
abbrev('BURGAN' , snU,3) |,
abbrev('BERGAN' , snU,3) |,
abbrev('BERGEN' , snU,3) Then sn= "BERGEN"
When abbrev('CENTIGRADE' , snU) |,
abbrev('CENTRIGRADE' , snU) |, /* 50% misspelled.*/
abbrev('CETIGRADE' , snU) |, /* 50% misspelled.*/
abbrev('CENTINGRADE' , snU) |,
abbrev('CENTESIMAL' , snU) |,
abbrev('CELCIU' , snU) |, /* 82% misspelled.*/
abbrev('CELCIOU' , snU) |, /* 4% misspelled.*/
abbrev('CELCUI' , snU) |, /* 4% misspelled.*/
abbrev('CELSUI' , snU) |, /* 2% misspelled.*/
abbrev('CELCEU' , snU) |, /* 2% misspelled.*/
abbrev('CELCU' , snU) |, /* 2% misspelled.*/
abbrev('CELISU' , snU) |, /* 1% misspelled.*/
abbrev('CELSU' , snU) |, /* 1% misspelled.*/
abbrev('HECTOGRADE' , snU) |,
abbrev('CELSIU' , snU) Then sn= "CELSIUS"
When abbrev('CIMANTO' , snU,2) |,
abbrev('CIMENTO' , snU,2) Then sn= "CIMENTO"
When abbrev('CRUQUIOU' , snU,2) |,
abbrev('CRUQUIO' , snU,2) |,
abbrev('CRUQUIU' , snU,2) Then sn= "CRUQUIU"
When abbrev('DALANCE' , snU,4) |,
abbrev('DALENCE' , snU,4) Then sn= "DALENCE"
When abbrev('DANELLE' , snU,3) |,
abbrev('DANEAL' , snU,3) |,
abbrev('DANIAL' , snU,3) |,
abbrev('DANIELE' , snU,3) |,
abbrev('DANNEL' , snU,3) |,
abbrev('DANYAL' , snU,3) |,
abbrev('DANYEL' , snU,3) |,
abbrev('DANIELL' , snU,3) Then sn= "DANIELL"
When abbrev('DALTON' , snU,3) Then sn= "DALTON"
When abbrev('DELAHIRE' , snU,7) |,
abbrev('LAHIRE' , snU,4) |,
abbrev('HIRE' , snU,2) |,
abbrev('DE-LA-HIRE' , snU,7) Then sn= "DE LA HIRE"
When abbrev('DELAVILLE' , snU,7) |,
abbrev('LAVILLE' , snU,3) |,
abbrev('VILLE' , snU,1) |,
abbrev('VILLA' , snU,1) |,
abbrev('DE-LA-VILLE' , snU,7) Then sn= "DE LA VILLE"
When abbrev('DELISLE' , snU,3) Then sn= "DELISLE"
When abbrev('DELISLE-OLD' , snU,8) |,
abbrev('OLDDELISLE' , snU,6) |,
abbrev('DELISLEOLD' , snU,8) Then sn= "DELISLE OLD"
When abbrev('DELUC' , snU,4) |,
abbrev('LUC' , snU,2) |,
abbrev('DE-LUC' , snU,5) Then sn= "DE LUC"
When abbrev('DELYON' , snU,4) |,
abbrev('LYON' , snU,2) |,
abbrev('DE-LYON' , snU,5) Then sn= "DE LYON"
When abbrev('DEREVILLA' , snU,3) |,
abbrev('DEREVILA' , snU,3) |,
abbrev('REVILLA' , snU,3) |,
abbrev('DE-REVILLA' , snU,4) |,
abbrev('DE-REVILLA' , snU,5) Then sn= "DE REVILLAS"
When abbrev('DEVILLENEUVE' , snU,3) |,
abbrev('DE-VILLENEUVE' , snU,4) Then sn= "DE VILLENEUVE"
When abbrev('DURHAM' , snU,3) |,
abbrev('DERHAM' , snU,4) Then sn= "DERHAM"
When abbrev('OLDDURHAM' , snU,5) |,
abbrev('OLDDERHAM' , snU,6) |,
abbrev('DERHAM-OLD' , snU,4) |,
abbrev('DERHAMOLD' , snU,4) Then sn= "DERHAM OLD"
When abbrev('DE-SUEDE' , snU,4) |,
abbrev('DESUEDE' , snU,4) Then sn= "DE SUEDE"
When abbrev('DU-CREST' , snU,2) |,
abbrev('DUCREST' , snU,2) Then sn= "DU CREST"
When abbrev('EDENBURGH' , snU,2) |,
abbrev('EDINBURGH' , snU,2) Then sn= "EDINBURGH"
When abbrev('EVOLT' , snU,2) |,
abbrev('ELECTRONVOLT' , snU,2) Then sn= "ELECTRON VOLTS"
When abbrev('FARENHEIT' , snU) |, /* 39% misspelled.*/
abbrev('FARENHEIGHT' , snU) |, /* 15% misspelled.*/
abbrev('FARENHITE' , snU) |, /* 6% misspelled.*/
abbrev('FARENHIET' , snU) |, /* 3% misspelled.*/
abbrev('FARHENHEIT' , snU) |, /* 3% misspelled.*/
abbrev('FARINHEIGHT' , snU) |, /* 2% misspelled.*/
abbrev('FARENHIGHT' , snU) |, /* 2% misspelled.*/
abbrev('FAHRENHIET' , snU) |, /* 2% misspelled.*/
abbrev('FERENHEIGHT' , snU) |, /* 2% misspelled.*/
abbrev('FEHRENHEIT' , snU) |, /* 2% misspelled.*/
abbrev('FERENHEIT' , snU) |, /* 2% misspelled.*/
abbrev('FERINHEIGHT' , snU) |, /* 1% misspelled.*/
abbrev('FARIENHEIT' , snU) |, /* 1% misspelled.*/
abbrev('FARINHEIT' , snU) |, /* 1% misspelled.*/
abbrev('FARANHITE' , snU) |, /* 1% misspelled.*/
abbrev('FAHRENHEIT' , snU) Then sn= "FAHRENHEIT"
When abbrev('OLDFAHRENHEIT' , snU,4) |,
abbrev('FAHRENHEIT-OLD' , snU,13) |,
abbrev('FAHRENHEITOLD' , snU,13) Then sn= "FARHENHEIT OLD"
When abbrev('FLORENTINE-LARGE' , snU,12) |,
abbrev('LARGE-FLORENTINE' , snU,7) |,
abbrev('LARGEFLORENTINE' , snU,6) |,
abbrev('FLORENTINELARGE' , snU,12) Then sn= "FLORENTINE LARGE"
When abbrev('FLORENTINE-MAGNUM' , snU,2) |,
abbrev('MAGNUM-FLORENTINE' , snU,3) |,
abbrev('MAGNUMFLORENTINE' , snU,3) |,
abbrev('FLORENTINEMAGNUM' , snU,2) Then sn= "FLORENTINE MAGNUM"
When abbrev('FLORENTINE-SMALL' , snU,13) |,
abbrev('SMALL-FLORENTINE' , snU,7) |,
abbrev('SMALLFLORENTINE' , snU,6) |,
abbrev('FLORENTINESMALL' , snU,13) Then sn= "FLORENTINE SMALL"
When abbrev('FOULER' , snU,2) |,
abbrev('FOWLOR' , snU,2) |,
abbrev('FOWLER' , snU,2) Then sn= "FOWLER"
When abbrev('FRICK' , snU,2) Then sn= "FRICK"
When abbrev('GAS-MARK' , snU,2) |,
abbrev('GASMARK' , snU,2) Then sn= "GAS MARK"
When abbrev('GOUBERT' , snU,2) Then sn= "GOUBERT"
When abbrev('HAIL' , snU,3) |,
abbrev('HALE' , snU,3) Then sn= "HALES"
When abbrev('HANOW' , snU,3) Then sn= "HANOW"
When abbrev('HUCKSBEE' , snU,3) |,
abbrev('HAWKSBEE' , snU,3) |,
abbrev('HAUKSBEE' , snU,3) Then sn= "HAUKSBEE"
When abbrev('JACOBSHOLBORN' , snU,2) |,
abbrev('JACOBS-HOLBORN' , snU,2) Then sn= "JACOBS-HOLBORN"
When abbrev('KALVIN' , snU) |, /* 27% misspelled.*/
abbrev('KERLIN' , snU) |, /* 18% misspelled.*/
abbrev('KEVEN' , snU) |, /* 9% misspelled.*/
abbrev('KELVIN' , snU) Then sn= "KELVIN"
When abbrev('LAYDEN' , snU) |,
abbrev('LEIDEN' , snU) Then sn= "LEIDEN"
When abbrev('NEUTON' , snU) |, /*100% misspelled.*/
abbrev('NEWTON' , snU) Then sn= "NEWTON"
When abbrev('ORTEL' , snU) |,
abbrev('OERTEL' , snU) Then sn= "OERTEL"
When abbrev('PLACK' , snU) |, /*100% misspelled.*/
abbrev('PLANC' , snU) |, /* misspelled.*/
abbrev('PLANK' , snU) |, /* misspelled.*/
abbrev('PLANCK' , snU) Then sn= "PLANCK"
When abbrev('RANKINE' , snU, 1) Then sn= "RANKINE"
When abbrev('REAUMUR' , snU, 2) Then sn= "REAUMUR"
When abbrev('RICKTER' , snU, 3) |,
abbrev('RICHTER' , snU, 3) Then sn= "RICHTER"
When abbrev('RINALDINI' , snU, 3) Then sn= "RINALDINI"
When abbrev('ROEMER' , snU, 3) |,
abbrev('ROMER' , snU, 3) Then sn= "ROMER"
When abbrev('ROSANTHAL' , snU, 3) |,
abbrev('ROSENTHAL' , snU, 3) Then sn= "ROSENTHAL"
When abbrev('RSOL' , snU, 2) |,
abbrev('RSL' , snU, 2) |,
abbrev('ROYALSOCIETYOFLONDON' , snU, 3) |,
abbrev('ROYAL-SOCIETY-OF-LONDON' , snU, 3) Then sn= "ROYAL SOCIETY"
When abbrev('SAGREDO' , snU, 3) Then sn= "SAGREDO"
When abbrev('ST.-PATRICE' , snU, 3) |,
abbrev('ST.PATRICE' , snU, 3) |,
abbrev('SAINTPATRICE' , snU, 3) |,
abbrev('SAINT-PATRICE' , snU, 3) Then sn= "SAINT-PATRICE"
When abbrev('STUFFE' , snU, 3) |,
abbrev('STUFE' , snU, 3) Then sn= "STUFE"
When abbrev('SULTZER' , snU, 2) |,
abbrev('SULZER' , snU, 2) Then sn= "SULZER"
When abbrev('WEDGEWOOD' , snU) |,
abbrev('WEDGWOOD' , snU) Then sn= "WEDGWOOD"
Otherwise
sn='***' sn '***'
End /*Select*/
Return sn

convert2Fahrenheit: /*convert N --? ºF temperatures. */
/* [?] fifty-eight temperature scales.*/
Parse Arg n sn
Select
When sn=='ABSOLUTE' Then F= n * 9/5 - 459.67
When sn=='AMONTON' Then F= n * 8.37209 - 399.163
When sn=='BARNSDORF' Then F= n * 6.85714 + 6.85714
When sn=='BEAUMUIR' Then F= n * 2.22951 + 32
When sn=='BENART' Then F= n * 1.43391 + 31.2831
When sn=='BERGEN' Then F=(n + 23.8667) * 15/14
When sn=='BRISSEN' Then F= n * 32/15 + 32
When sn=='CELSIUS' Then F= n * 9/5 + 32 /* C -> Celsius.*/
When sn=='CIMENTO' Then F= n * 2.70677 - 4.54135
When sn=='CRUQUIUS' Then F= n * 0.409266 - 405.992
When sn=='DALENCE' Then F= n * 2.7 + 59
When sn=='DALTON' Then F=rxCalcexp(rxCalclog(373.15/273.15)*n/100)*9*273.15/5-459.67
--When sn=='DALTON' Then F=273.15*rxCalcexp(273.15/273.15,n/100)*1.8-459.67
When sn=='DANIELL' Then F= n * 7.27194 + 55.9994
When sn=='DE LA HIRE' Then F=(n - 3) / 0.549057
When sn=='DE LA VILLE' Then F=(n + 6.48011) / 0.985568
When sn=='DELISLE' Then F=212 - n * 6/5
When sn=='DELISLE OLD' Then F=212 - n * 1.58590197
When sn=='DE LUC' Then F=(n + 14) * 16/7
When sn=='DE LYON' Then F=(n + 17.5) * 64/35
When sn=='DE REVILLAS' Then F=212 - n * 97/80
When sn=='DERHAM' Then F= n / 0.38444386 - 188.578
When sn=='DERHAM OLD' Then F= n * 3 + 4.5
When sn=='DE SUEDE' Then F=(n + 17.6666) * 150/83
When sn=='DE VILLENEUVE' Then F=(n + 23.7037) / 0.740741
When sn=='DU CREST' Then F=(n + 37.9202) / 0.650656
When sn=='EDINBURGH' Then F= n * 4.6546 - 6.40048
When sn=='ELECTRON VOLTS' Then F= n * 20888.1 - 459.67
When sn=='FAHRENHEIT' Then F= n
When sn=='FAHRENHEIT OLD' Then F= n * 20/11 - 89.2727
When sn=='FLORENTINE LARGE' Then F=(n + 7.42857) / 0.857143
When sn=='FLORENTINE MAGNUM' Then F=(n + 73.9736 ) / 1.50659
When sn=='FLORENTINE SMALL' Then F=(n - 1.38571) / 0.378571
When sn=='FOWLER' Then F= n * 0.640321 + 53.7709
When sn=='FRICK' Then F= n * 200/251 + 58.5339
When sn=='GASMARK' Then F= n * 25 + 250
When sn=='GOUBERT' Then F= n * 2 + 32
When sn=='HALES' Then F= n * 1.2 + 32
When sn=='HANOW' Then F= n * 1.06668 - 10.6672
When sn=='HAUKSBEE' Then F= n * 18/25 + 88.16
When sn=='JACOBS-HOLBORN' Then F= n * 18/71 - 53.4366
When sn=='K' Then F= n * 9/5 - 459.67
When sn=='KELVIN' Then F= n * 9/5 - 459.67
When sn=='LEIDEN' Then F= n * 1.8 - 423.4
When sn=='NEWTON' Then F= n * 60/11 + 32
When sn=='OERTEL' Then F= n + n - 32
When sn=='PLANCK' Then F= n * 1.416833e32* 9/5 - 459.67
When sn=='RANKINE' Then F= n - 459.67 /* R -> Rankine.*/
When sn=='REAUMUR' Then F= n * 9/4 + 32
When sn=='RICHTER' Then F= n * 160/73 - 7.45205
When sn=='RINALDINI' Then F= n * 15 + 32
When sn=='ROMER' Then F=(n - 7.5) * 27/4+ 32
When sn=='ROSENTHAL' Then F= n * 45/86 - 453.581
When sn=='ROYAL SOCIETY' Then F=(n -122.82) * -50/69
When sn=='SAGREDO' Then F= n * 0.3798 - 5.98
When sn=='SAINT-PATRICE' Then F= n * 2.62123 + 115.879
When sn=='STUFE' Then F= n * 45 + 257
When sn=='SULZER' Then F= n * 1.14595 + 33.2334
When sn=='THERMOSTAT' Then F= n * 54 + 32
When sn=='WEDGWOOD' Then F= n * 44.7429295 + 516.2
Otherwise Call serr 'invalid temperature scale: '
End /*Select*/
Return F

convert2specific: /*convert ºF --? xxx temperatures.*/

K=(F+459.67)*5/9 /*compute temperature in kelvin scale. */
a=(1e||(-digits()%2)-digits()%20) /*minimum number for Dalton temperature*/
eV=(F+459.67)/20888.1 /*compute the number of electron volts.*/

If ?('ABSOLUTE') Then Call line fn(k) "Absolute"
If ?('AMONTON') Then Call line fn((F+399.163) / 8.37209 ) "Amonton"
If ?('BARNSDORF') Then Call line fn( ( F - 6.85715) / 6.85715 ) "Barnsdorf"
If ?('BEAUMUIR') Then Call line fn( ( F - 32 ) / 2.22951 ) "Beaumuir"
If ?('BENART') Then Call line fn( ( F - 31.2831 ) / 1.43391 ) "Benart"
If ?('BERGEN') Then Call line fn( ( F * 14/15 ) - 23.8667 ) "Bergen"
If ?('BRISSON') Then Call line fn( ( F - 32 ) * 15/32 ) "Brisson"
If ?('CELSIUS') Then Call line fn( ( F - 32 ) * 5/9 ) "Celsius"
If ?('CIMENTO') Then Call line fn( ( F + 4.54135) / 2.70677 ) "Cimento"
If ?('CRUQUIUS') Then Call line fn( ( F + 405.992 ) / 0.409266 ) "Cruquius"
If ?('DALENCE') Then Call line fn( ( F - 59 ) / 2.7 ) "Dalence"
If ?('DALTON') Then Do
If K>a Then Call line fn(100*rxCalclog(k/273.15)/rxCalclog(373.15/273.15) ) "Dalton"
Else Call line right("-infinity ", 60) "Dalton"
End
If ?('DANIELL') Then Call line fn( ( F - 55.9994 ) / 7.27194 ) "Daniell"
If ?('DE LA HIRE') Then Call line fn( F * 0.549057 + 3 ) "De la Hire"
If ?('DE LA VILLE') Then Call line fn( F * 0.985568 - 6.48011 ) "De la Ville"
If ?('DELISLE') Then Call line fn( ( 212 - F ) * 5/6 ) "Delisle"
If ?('DELISLE OLD') Then Call line fn( ( 212 - F ) / 1.58590197 ) "Delisle OLD"
If ?('DE LUC') Then Call line fn( F * 7/16 - 14 ) "De Luc"
If ?('DE LYON') Then Call line fn( F * 35/64 - 17.5 ) "De Lyon"
If ?('DE REVILLAS') Then Call line fn( ( 212 - F ) * 80/97 ) "De Revillas"
If ?('DERHAM') Then Call line fn( F * 0.38444386 + 72.4978 ) "Derham"
If ?('DERHAM OLD') Then Call line fn( ( F - 4.5 ) / 3 ) "Derham OLD"
If ?('DE VILLENEUVE') Then Call line fn( F * 0.740741 - 23.7037 ) "De Villeneuve"
If ?('DE SUEDE') Then Call line fn( F * 83/150 - 17.6666 ) "De Suede"
If ?('DU CREST') Then Call line fn( F * 0.650656 - 37.9202 ) "Du Crest"
If ?('EDINBURGH') Then Call line fn( ( F + 6.40048) / 4.6546 ) "Edinburgh"
If ?('ELECTRON VOLTS') Then Call line fn( eV ) "electron volt"s(eV)
If ?('FAHRENHEIT') Then Call line fn( F ) "Fahrenheit"
If ?('FAHRENHEIT OLD') Then Call line fn( F * 20/11 - 89.2727 ) "Fahrenheit OLD"
If ?('FLORENTINE LARGE') Then Call line fn( F * 0.857143 - 7.42857 ) "Florentine large"
If ?('FLORENTINE MAGNUM') Then Call line fn( F * 1.50659 - 73.9736 ) "Florentine Magnum"
If ?('FLORENTINE SMALL') Then Call line fn( F * 0.378571 + 1.38571 ) "Florentine small"
If ?('FOWLER') Then Call line fn( ( F - 53.7709 ) / 0.640321 ) "Fowler"
If ?('FRICK') Then Call line fn( ( F - 58.5338 ) * 251/200 ) "Frick"
If ?('GAS MARK') Then Call line fn( ( F - 250 ) * 0.04 ) "gas mark"
If ?('GOUBERT') Then Call line fn( ( F + 32 ) * 0.5 ) "Goubert"
If ?('HALES') Then Call line fn( ( F - 32 ) / 1.2 ) "Hales"
If ?('HANOW') Then Call line fn( ( F + 10.6672 ) / 1.06668 ) "Hanow"
If ?('HAUKSBEE') Then Call line fn( ( F - 88.16 ) * 25/18 ) "Hauksbee"
If ?('JACOBS-HOLBORN') Then Call line fn( ( F + 53.4366 ) * 71/18 ) "Jacobs-Holborn"
If ?('KELVIN') Then Call line fn( k ) 'KELVIN'
If ?('LEIDEN') Then Call line fn( F / 1.8 + 235.222 ) "Leiden"
If ?('NEWTON') Then Call line fn( ( F - 32 ) * 11/60 ) "Newton"
If ?('OERTEL') Then Call line fn( ( F + 32 ) * 0.5 ) "Oertel"
If ?('PLANCK') Then Call line fn( ( F + 459.67 ) * 5/9 / 1.416833e32 ) "Planck"
If ?('RANKINE') Then Call line fn( F + 459.67 ) "Rankine"
If ?('REAUMUR') Then Call line fn( ( F - 32 ) * 4/9 ) "Reaumur"
If ?('RICHTER') Then Call line fn( ( F + 7.45205) * 73/160 ) "Richter"
If ?('RINALDINI') Then Call line fn( ( F - 32 ) / 15 ) "Rinaldini"
If ?('ROMER') Then Call line fn( ( F - 32 ) * 4/27 + 7.5 ) "Romer"
If ?('ROSENTHAL') Then Call line fn( ( F + 453.581 ) * 86/45 ) "Rosenthal"
If ?('ROYAL SOCIETY') Then Call line fn( F * -69/50 + 122.82 ) "Royal Society of London"
If ?('SAGREDO') Then Call line fn( ( F + 5.98 ) / 0.3798 ) "Segredo"
If ?('SAINT-PATRICE') Then Call line fn( ( F - 115.879 ) / 2.62123 ) "Saint-Patrice"
If ?('STUFE') Then Call line fn( ( F - 257 ) / 45 ) "Stufe"
If ?('SULZER') Then Call line fn( ( F - 33.2334 ) / 1.14595 ) "Sulzer"
If ?('THERMOSTAT') Then Call line fn( ( F - 32 ) / 54 ) "Thermostat"
If ?('WEDGWOOD') Then Call line fn( ( F - 516.2 ) / 44.7429295 ) "Wedgwood"
Return

line:
If how='FUNCTION' & all=0 Then
Exit space(arg(1))
Else
Say arg(1)
Return

?:
Return (arg(1)=toscale | all)

fn: Procedure Expose how result
showDig=8 /* only show 8 decimal digs. */
number=commas(format(arg(1),,showDig)/1) /* format# 8 digits past . and add commas */
p=pos('.',number) /* find position of the decimal point. */
/* [?] align integers with FP numbers. */
If p==0 Then /* no decimal point .*/
number=number||left('',5+showDig+1)
Else /* ddd.ddd */
number=number||left('',5+showDig-length(number)+p)
Return right(number,max(25,length(number)))/* return the re-formatted argument (#).*/

commas: Procedure
Parse Arg u
a=pos('.',u'.')
e=1
If left(u,1)='-' Then e=2
Do j=a-4 To e by -3
u=insert(',',u,j)
End
Return u

s:
If arg(1)==1 Then Return arg(3)
Return word(arg(2)'s',1) /*pluralizer.*/

serr:
If how='FUNCTION' Then
Exit arg(1)
Else
Say arg(1)
Exit 13

help:
Say 'use as command:'
Say 'rexx tcw fromtemp [fromscale] [TO toscale | all],...'
Say 'or as function'
Say 'tcw(fromtemp [fromscale] [TO toscale])'
Exit
::Requires rxmath library
</syntaxhighlight>

{{out}}
<pre>
K:\_B\TC>rexx tcwoo 0 C to fa
0 C to fa
0 CELSIUS TO FAHRENHEIT
32 Fahrenheit
K:\_B\TC>rexx tcwoo 0 f
0 f
0 FAHRENHEIT TO all
255.372222 Absolute
47.67782 Amonton
-1 Barnsdorf
-14.3529296 Beaumuir
-21.8166412 Benart
-23.8667 Bergen
-15 Brisson
-17.7777778 Celsius
1.67777462 Cimento
992.000313 Cruquius
-21.8518519 Dalence
-21.5729747 Dalton
-7.70075111 Daniell
3 De la Hire
-6.48011 De la Ville
176.666667 Delisle
133.677872 Delisle OLD
-14 De Luc
-17.5 De Lyon
174.845361 De Revillas
72.4978 Derham
-1.5 Derham OLD
-23.7037 De Villeneuve
-17.6666 De Suede
-37.9202 Du Crest
1.37508701 Edinburgh
0.02200631 electron volts
0 Fahrenheit
-89.2727 Fahrenheit OLD
-7.42857 Florentine large
-73.9736 Florentine Magnum
1.38571 Florentine small
-83.9749126 Fowler
-73.459919 Frick
-10 gas mark
16 Goubert
-26.6666667 Hales
10.000375 Hanow
-122.444444 Hauksbee
210.7777 Jacobs-Holborn
255.372222 KELVIN
235.222 Leiden
-5.86666667 Newton
16 Oertel
1.80241582E-30 Planck
459.67 Rankine
-14.2222222 Reaumur
3.39999781 Richter
-2.13333333 Rinaldini
2.75925926 Romer
866.843689 Rosenthal
122.82 Royal Society of London
15.745129 Segredo
-44.2078719 Saint-Patrice
-5.71111111 Stufe
-29.0007417 Sulzer
-0.59259259 Thermostat
-11.5370184 Wedgwood
</pre>
</pre>


=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
<lang parigp>f(x)=[x,x-273.15,1.8*x-459.67,1.8*x]</lang>
<syntaxhighlight lang="parigp">f(x)=[x,x-273.15,1.8*x-459.67,1.8*x]</syntaxhighlight>


=={{header|Pascal}}==
=={{header|Pascal}}==
<lang Pascal>program TemperatureConvert;
<syntaxhighlight lang="pascal">program TemperatureConvert;


type
type
Line 3,080: Line 3,784:
writeln(' ', ConvertTemperature(kelvin, K, F) : 3 : 2, ' in degrees Fahrenheit.');
writeln(' ', ConvertTemperature(kelvin, K, F) : 3 : 2, ' in degrees Fahrenheit.');
writeln(' ', ConvertTemperature(kelvin, K, R) : 3 : 2, ' in degrees Rankine.');
writeln(' ', ConvertTemperature(kelvin, K, R) : 3 : 2, ' in degrees Rankine.');
end.</lang>
end.</syntaxhighlight>


{{out}}
{{out}}
Line 3,092: Line 3,796:


=={{header|Perl}}==
=={{header|Perl}}==
<lang Perl>my %scale = (
<syntaxhighlight lang="perl">my %scale = (
Celcius => { factor => 1 , offset => -273.15 },
Celcius => { factor => 1 , offset => -273.15 },
Rankine => { factor => 1.8, offset => 0 },
Rankine => { factor => 1.8, offset => 0 },
Line 3,104: Line 3,808:
foreach (sort keys %scale) {
foreach (sort keys %scale) {
printf "%12s:%8.2f\n", $_, $kelvin * $scale{$_}{factor} + $scale{$_}{offset};
printf "%12s:%8.2f\n", $_, $kelvin * $scale{$_}{factor} + $scale{$_}{offset};
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,115: Line 3,819:
=={{header|Phix}}==
=={{header|Phix}}==
Modified copy of [[Temperature_conversion#Euphoria|Euphoria]]
Modified copy of [[Temperature_conversion#Euphoria|Euphoria]]
<!--<lang Phix>-->
<!--<syntaxhighlight lang="phix">-->
<span style="color: #004080;">atom</span> <span style="color: #000000;">K</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">prompt_number</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"Enter temperature in Kelvin >=0: "</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1e307</span><span style="color: #0000FF;">})</span>
<span style="color: #004080;">atom</span> <span style="color: #000000;">K</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">prompt_number</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"Enter temperature in Kelvin >=0: "</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1e307</span><span style="color: #0000FF;">})</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">" Kelvin: %5.2f\n Celsius: %5.2f\nFahrenheit: %5.2f\n Rankine: %5.2f\n\n"</span><span style="color: #0000FF;">,</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">" Kelvin: %5.2f\n Celsius: %5.2f\nFahrenheit: %5.2f\n Rankine: %5.2f\n\n"</span><span style="color: #0000FF;">,</span>
<span style="color: #0000FF;">{</span><span style="color: #000000;">K</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">K</span><span style="color: #0000FF;">-</span><span style="color: #000000;">273.15</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">K</span><span style="color: #0000FF;">*</span><span style="color: #000000;">1.8</span><span style="color: #0000FF;">-</span><span style="color: #000000;">459.67</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">K</span><span style="color: #0000FF;">*</span><span style="color: #000000;">1.8</span><span style="color: #0000FF;">})</span>
<span style="color: #0000FF;">{</span><span style="color: #000000;">K</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">K</span><span style="color: #0000FF;">-</span><span style="color: #000000;">273.15</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">K</span><span style="color: #0000FF;">*</span><span style="color: #000000;">1.8</span><span style="color: #0000FF;">-</span><span style="color: #000000;">459.67</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">K</span><span style="color: #0000FF;">*</span><span style="color: #000000;">1.8</span><span style="color: #0000FF;">})</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 3,130: Line 3,834:


=={{header|PHP}}==
=={{header|PHP}}==
<lang php>
<syntaxhighlight lang="php">


while (true) {
while (true) {
Line 3,149: Line 3,853:
}
}
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>Enter a value in kelvin (q to quit): 21
<pre>Enter a value in kelvin (q to quit): 21
Line 3,161: Line 3,865:


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<lang PicoLisp>(scl 2)
<syntaxhighlight lang="picolisp">(scl 2)


(de convertKelvin (Kelvin)
(de convertKelvin (Kelvin)
Line 3,172: Line 3,876:
(tab (-3 8)
(tab (-3 8)
(car X)
(car X)
(format ((cdr X) Kelvin) *Scl) ) ) )</lang>
(format ((cdr X) Kelvin) *Scl) ) ) )</syntaxhighlight>
Test:
Test:
<lang PicoLisp>(convertKelvin 21.0)</lang>
<syntaxhighlight lang="picolisp">(convertKelvin 21.0)</syntaxhighlight>
{{out}}
{{out}}
<pre>K 21.00
<pre>K 21.00
Line 3,182: Line 3,886:


=={{header|PL/I}}==
=={{header|PL/I}}==
<lang pli>*process source attributes xref;
<syntaxhighlight lang="pli">*process source attributes xref;
/* PL/I **************************************************************
/* PL/I **************************************************************
* 15.08.2013 Walter Pachl translated from NetRexx
* 15.08.2013 Walter Pachl translated from NetRexx
Line 3,329: Line 4,033:
End;
End;
End;
End;
End;</lang>
End;</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,345: Line 4,049:


=={{header|Plain English}}==
=={{header|Plain English}}==
<lang plainenglish>To run:
<syntaxhighlight lang="plainenglish">To run:
Start up.
Start up.
Put 21 into a kelvin temperature.
Put 21 into a kelvin temperature.
Line 3,378: Line 4,082:
Show the celsius temperature given "C".
Show the celsius temperature given "C".
Show the fahrenheit temperature given "F".
Show the fahrenheit temperature given "F".
Show the rankine temperature given "R".</lang>
Show the rankine temperature given "R".</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,389: Line 4,093:
=={{header|PowerShell}}==
=={{header|PowerShell}}==
{{trans|Tcl}}
{{trans|Tcl}}
<lang powershell>function temp($k){
<syntaxhighlight lang="powershell">function temp($k){
try{
try{
$c = $k - 273.15
$c = $k - 273.15
Line 3,409: Line 4,113:


$input=Read-host "Enter a temperature in Kelvin"
$input=Read-host "Enter a temperature in Kelvin"
temp $input</lang>
temp $input</syntaxhighlight>
{{Out}}
{{Out}}
<pre>PS> ./TEMPS
<pre>PS> ./TEMPS
Line 3,423: Line 4,127:
===PowerShell Alternate Version===
===PowerShell Alternate Version===
A more "PowerShelly" way to do it.
A more "PowerShelly" way to do it.
<syntaxhighlight lang="powershell">function Convert-Kelvin
<lang PowerShell>
function Convert-Kelvin
{
{
[CmdletBinding()]
[CmdletBinding()]
Line 3,450: Line 4,153:
}
}
}
}
}</syntaxhighlight>
}
<syntaxhighlight lang="powershell">
</lang>
<lang PowerShell>
21, 100 | Convert-Kelvin
21, 100 | Convert-Kelvin
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
Line 3,462: Line 4,164:
100 -173.15 -279.67 180
100 -173.15 -279.67 180
</pre>
</pre>

=={{header|Prolog}}==
{{works with|GNU Prolog}}
{{works with|SWI Prolog}}
<syntaxhighlight lang="prolog">convKelvin(Temp) :-
Kelvin is Temp,
Celsius is Temp - 273.15,
Fahrenheit is (Temp - 273.15) * 1.8 + 32.0,
Rankine is (Temp - 273.15) * 1.8 + 32.0 + 459.67,
format('~f degrees Kelvin~n', [Kelvin]),
format('~f degrees Celsius~n', [Celsius]),
format('~f degrees Fahrenheit~n', [Fahrenheit]),
format('~f degrees Rankine~n', [Rankine]).

test :-
convKelvin(0.0),
nl,
convKelvin(21.0).</syntaxhighlight>


=={{header|Pure Data}}==
=={{header|Pure Data}}==

'''temperature.pd'''
'''temperature.pd'''
<pre>#N canvas 200 200 640 600 10;
<pre>
#N canvas 200 200 640 600 10;
#X floatatom 130 54 8 0 0 2 Kelvin chgk -;
#X floatatom 130 54 8 0 0 2 Kelvin chgk -;
#X obj 130 453 rnd2;
#X obj 130 453 rnd2;
Line 3,531: Line 4,249:
#X connect 24 0 4 0;
#X connect 24 0 4 0;
#X connect 25 0 26 0;
#X connect 25 0 26 0;
#X connect 26 0 7 0;
#X connect 26 0 7 0;</pre>
</pre>
Plugin to round the results to at most 2 digits:
Plugin to round the results to at most 2 digits:


'''rnd.pd'''
'''rnd.pd'''
<pre>#N canvas 880 200 450 300 10;
<pre>
#N canvas 880 200 450 300 10;
#X obj 77 34 inlet;
#X obj 77 34 inlet;
#X obj 77 113 * 100;
#X obj 77 113 * 100;
Line 3,553: Line 4,269:
#X connect 4 0 5 0;
#X connect 4 0 5 0;
#X connect 5 0 6 0;
#X connect 5 0 6 0;
#X connect 6 0 7 0;
#X connect 6 0 7 0;</pre>
</pre>

=={{header|PureBasic}}==
<lang purebasic>Procedure.d Kelvin2Celsius(tK.d) : ProcedureReturn tK-273.15 : EndProcedure
Procedure.d Kelvin2Fahrenheit(tK.d) : ProcedureReturn tK*1.8-459.67 : EndProcedure
Procedure.d Kelvin2Rankine(tK.d) : ProcedureReturn tK*1.8 : EndProcedure

OpenConsole()
Repeat
Print("Temperatur Kelvin? ") : Kelvin.d = ValD(Input())
PrintN("Conversion:")
PrintN(#TAB$+"Celsius "+#TAB$+RSet(StrD(Kelvin2Celsius(Kelvin),2),8,Chr(32)))
PrintN(#TAB$+"Fahrenheit"+#TAB$+RSet(StrD(Kelvin2Fahrenheit(Kelvin),2),8,Chr(32)))
PrintN(#TAB$+"Rankine "+#TAB$+RSet(StrD(Kelvin2Rankine(Kelvin),2),8,Chr(32)))
PrintN("ESC = End.")
Repeat
k$=Inkey() : Delay(50) : If RawKey()=#ESC : End : EndIf
Until RawKey()
ForEver</lang>
<pre>Temperatur Kelvin? 21
Conversion:
Celsius -252.15
Fahrenheit -421.87
Rankine 37.80
ESC = End.</pre>


=={{header|Python}}==
=={{header|Python}}==
<lang python>>>> while True:
<syntaxhighlight lang="python">>>> while True:
k = float(input('K ? '))
k = float(input('K ? '))
print("%g Kelvin = %g Celsius = %g Fahrenheit = %g Rankine degrees."
print("%g Kelvin = %g Celsius = %g Fahrenheit = %g Rankine degrees."
Line 3,591: Line 4,282:
K ? 222.2
K ? 222.2
222.2 Kelvin = -50.95 Celsius = -59.71 Fahrenheit = 399.96 Rankine degrees.
222.2 Kelvin = -50.95 Celsius = -59.71 Fahrenheit = 399.96 Rankine degrees.
K ? </lang>
K ? </syntaxhighlight>


===Python: Universal conversion===
===Python: Universal conversion===
This converts from any one of the units to all the others
This converts from any one of the units to all the others
<lang python>>>> toK = {'C': (lambda c: c + 273.15),
<syntaxhighlight lang="python">>>> toK = {'C': (lambda c: c + 273.15),
'F': (lambda f: (f + 459.67) / 1.8),
'F': (lambda f: (f + 459.67) / 1.8),
'R': (lambda r: r / 1.8),
'R': (lambda r: r / 1.8),
Line 3,614: Line 4,305:
<value> <K/R/F/C> ? 399.96 R
<value> <K/R/F/C> ? 399.96 R
222.2 Kelvin = -50.95 Celsius = -59.71 Fahrenheit = 399.96 Rankine degrees.
222.2 Kelvin = -50.95 Celsius = -59.71 Fahrenheit = 399.96 Rankine degrees.
<value> <K/R/F/C> ? </lang>
<value> <K/R/F/C> ? </syntaxhighlight>


=={{header|Quackery}}==
=={{header|Quackery}}==

All the conversions.
All the conversions.


Using the Quackery big number rational arithmetic library <code>bigrat.qky</code>.
Using the Quackery big number rational arithmetic library <code>bigrat.qky</code>.


<lang Quackery> [ $ "bigrat.qky" loadfile ] now!
<syntaxhighlight lang="quackery"> [ $ "bigrat.qky" loadfile ] now!
[ 5 9 v* ] is r->k ( n/d --> n/d )
[ 5 9 v* ] is r->k ( n/d --> n/d )
Line 3,652: Line 4,342:
say " degrees Rankine" cr ] is task ( $ --> )
say " degrees Rankine" cr ] is task ( $ --> )
$ "21.00" task</lang>
$ "21.00" task</syntaxhighlight>

{{out}}
{{out}}

<pre>21 Kelvins is equal to
<pre>21 Kelvins is equal to
-252.15 degrees Celcius
-252.15 degrees Celcius
Line 3,663: Line 4,351:


=={{header|R}}==
=={{header|R}}==
<lang R>convert_Kelvin <- function(K){
<syntaxhighlight lang="r">convert_Kelvin <- function(K){
if (!is.numeric(K))
if (!is.numeric(K))
stop("\n Input has to be numeric")
stop("\n Input has to be numeric")
Line 3,677: Line 4,365:
convert_Kelvin(21)
convert_Kelvin(21)
</syntaxhighlight>
</lang>

{{out}}
{{out}}
<pre>
<pre> $Kelvin
$Kelvin
[1] 21
[1] 21
Line 3,691: Line 4,377:
$Rankine
$Rankine
[1] 37.8
[1] 37.8</pre>
</pre>


=={{header|Racket}}==
=={{header|Racket}}==
Although not exactly the shortest code,
Although not exactly the shortest code,
the converter function can turn any temperature into any other
the converter function can turn any temperature into any other
<lang Racket>#lang racket
<syntaxhighlight lang="racket">#lang racket
(define (converter temp init final)
(define (converter temp init final)
(define to-k
(define to-k
Line 3,722: Line 4,407:
;Fahrenheit: -421.87
;Fahrenheit: -421.87
;Rankine: 37.800000000000004
;Rankine: 37.800000000000004
</syntaxhighlight>
</lang>


=={{header|Raku}}==
=={{header|Raku}}==
Line 3,728: Line 4,413:


{{trans|Perl}}
{{trans|Perl}}
<lang perl6>my %scale =
<syntaxhighlight lang="raku" line>my %scale =
Celcius => { factor => 1 , offset => -273.15 },
Celcius => { factor => 1 , offset => -273.15 },
Rankine => { factor => 1.8, offset => 0 },
Rankine => { factor => 1.8, offset => 0 },
Line 3,739: Line 4,424:
for %scale.sort {
for %scale.sort {
printf "%12s: %7.2f\n", .key, $kelvin * .value<factor> + .value<offset>;
printf "%12s: %7.2f\n", .key, $kelvin * .value<factor> + .value<offset>;
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 3,751: Line 4,436:
Alternative version that accepts the input in any of the four scales:
Alternative version that accepts the input in any of the four scales:


<lang perl6>while my $answer = prompt 'Temperature: ' {
<syntaxhighlight lang="raku" line>while my $answer = prompt 'Temperature: ' {
my $k = do given $answer {
my $k = do given $answer {
when s/:i C $// { $_ + 273.15 }
when s/:i C $// { $_ + 273.15 }
Line 3,763: Line 4,448:
say " { $k * 1.8 - 459.67 }℉";
say " { $k * 1.8 - 459.67 }℉";
say " { $k * 1.8 }R";
say " { $k * 1.8 }R";
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>Temperature: 0
<pre>Temperature: 0
Line 3,811: Line 4,496:
::* comments (annotation notes) allowed within the list
::* comments (annotation notes) allowed within the list
::* aligned output (whole numbers and decimal fractions)
::* aligned output (whole numbers and decimal fractions)
<lang rexx>/*REXX program converts temperatures for a number (8) of temperature scales. */
<syntaxhighlight lang="rexx">/*REXX program converts temperatures for a number (8) of temperature scales. */
numeric digits 120 /*be able to support some huge numbers.*/
numeric digits 120 /*be able to support some huge numbers.*/
parse arg tList /*get the specified temperature list. */
parse arg tList /*get the specified temperature list. */
Line 3,834: Line 4,519:
if \all then do /*is there is a TO ααα scale? */
if \all then do /*is there is a TO ααα scale? */
call name ! /*process the TO abbreviation. */
call name ! /*process the TO abbreviation. */
!= s n /*assign the full name to ! */
!= sn /*assign the full name to ! */
end /*!: now contains temperature full name*/
end /*!: now contains temperature full name*/
call name u /*allow alternate scale (miss)spellings*/
call name u /*allow alternate scale (miss)spellings*/
Line 3,927: Line 4,612:
otherwise call serr 'illegal temperature scale:' y
otherwise call serr 'illegal temperature scale:' y
end /*select*/
end /*select*/
return</lang>
return</syntaxhighlight>
{{out|output|text=&nbsp; when using the input of: &nbsp; &nbsp; <tt> 98.6F to C, &nbsp; -40C, 0 c (water freezes), &nbsp; 37C (body temp), &nbsp; 100 C (water boils), &nbsp; 21 degrees Kelvin, &nbsp; 0 K (outer space?) </tt>}}
{{out|output|text=&nbsp; when using the input of: &nbsp; &nbsp; <tt> 98.6F to C, &nbsp; -40C, 0 c (water freezes), &nbsp; 37C (body temp), &nbsp; 100 C (water boils), &nbsp; 21 degrees Kelvin, &nbsp; 0 K (outer space?) </tt>}}
<pre>
<pre>
Line 4,127: Line 4,812:


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
k = 21.0 c = 0 r = 0 f = 0
k = 21.0 c = 0 r = 0 f = 0
convertTemp(k)
convertTemp(k)
Line 4,139: Line 4,824:
r = k * 1.8
r = k * 1.8
f = r - 459.67
f = r - 459.67
</syntaxhighlight>
</lang>

=={{header|RPL}}==
RPL has a built-in conversion feature with a convenient catalog of units.
≪ { "°C" "°F" "°R" } → tempk units
≪ 1 3 '''FOR''' j
tempk "°K" units j GET CONVERT
SWAP →STR SWAP +
'''NEXT'''
≫ ≫ 'K→CFR' STO

21 K→CFR
{{out}}
<pre>
3: "-252.15°C"
2: "-421.87°F"
1: "37.8°R"
</pre>


=={{header|Ruby}}==
=={{header|Ruby}}==
<lang ruby>module TempConvert
<syntaxhighlight lang="ruby">module TempConvert


FROM_TEMP_SCALE_TO_K =
FROM_TEMP_SCALE_TO_K =
Line 4,188: Line 4,890:
end
end
end</lang>
end</syntaxhighlight>
Converts all eight scales to any other scale, by means of method_missing.
Converts all eight scales to any other scale, by means of method_missing.


Usage:
Usage:
<lang ruby>TempConvert.kelvin_to_celsius 100 #=> -173.15
<syntaxhighlight lang="ruby">TempConvert.kelvin_to_celsius 100 #=> -173.15
TempConvert.kelvin_to_fahrenheit 100 #=> -279.67
TempConvert.kelvin_to_fahrenheit 100 #=> -279.67
TempConvert.kelvin_to_rankine 100 #=> 180.0
TempConvert.kelvin_to_rankine 100 #=> 180.0
Line 4,202: Line 4,904:
TempConvert.newton_to_celsius 100 #=> 303.03
TempConvert.newton_to_celsius 100 #=> 303.03
TempConvert.newton_to_fahrenheit 100 #=> 577.45
TempConvert.newton_to_fahrenheit 100 #=> 577.45
# All 64 combinations possible</lang>
# All 64 combinations possible</syntaxhighlight>


=={{header|Run BASIC}}==
=={{header|Run BASIC}}==
<lang runbasic>[loop]
<syntaxhighlight lang="runbasic">[loop]
input "Kelvin Degrees";kelvin
input "Kelvin Degrees";kelvin
if kelvin <= 0 then end ' zero or less ends the program
if kelvin <= 0 then end ' zero or less ends the program
Line 4,212: Line 4,914:
rankine = kelvin * 1.8
rankine = kelvin * 1.8
print kelvin;" kelvin is equal to ";celcius; " degrees celcius and ";fahrenheit;" degrees fahrenheit and ";rankine; " degrees rankine"
print kelvin;" kelvin is equal to ";celcius; " degrees celcius and ";fahrenheit;" degrees fahrenheit and ";rankine; " degrees rankine"
goto [loop]</lang>
goto [loop]</syntaxhighlight>


=={{header|Scala}}==
=={{header|Scala}}==
{{libheader|Scala}}
{{libheader|Scala}}
<lang Scala>object TemperatureConversion extends App {
<syntaxhighlight lang="scala">object TemperatureConversion extends App {


def kelvinToCelsius(k: Double) = k + 273.15
def kelvinToCelsius(k: Double) = k + 273.15
Line 4,242: Line 4,944:
}
}
} else println("Temperature not given.")
} else println("Temperature not given.")
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 4,252: Line 4,954:


=={{header|Rust}}==
=={{header|Rust}}==
<lang Rust>fn main() -> std::io::Result<()> {
<syntaxhighlight lang="rust">fn main() -> std::io::Result<()> {
print!("Enter temperature in Kelvin to convert: ");
print!("Enter temperature in Kelvin to convert: ");
let mut input = String::new();
let mut input = String::new();
Line 4,272: Line 4,974:


Ok(())
Ok(())
}</lang>
}</syntaxhighlight>


=={{header|Scheme}}==
=={{header|Scheme}}==


<lang scheme>
<syntaxhighlight lang="scheme">
(import (scheme base)
(import (scheme base)
(scheme read)
(scheme read)
Line 4,296: Line 4,998:
(display "Fahrenheit: ") (display (kelvin->fahrenheit k)) (newline)
(display "Fahrenheit: ") (display (kelvin->fahrenheit k)) (newline)
(display "Rankine : ") (display (kelvin->rankine k)) (newline)))
(display "Rankine : ") (display (kelvin->rankine k)) (newline)))
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 4,307: Line 5,009:


=={{header|Seed7}}==
=={{header|Seed7}}==
<lang seed7>$ include "seed7_05.s7i";
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "float.s7i";
include "float.s7i";


Line 4,329: Line 5,031:
writeln("F: " <& fahrenheit(kelvin) digits 2 lpad 7);
writeln("F: " <& fahrenheit(kelvin) digits 2 lpad 7);
writeln("R: " <& rankine(kelvin) digits 2 lpad 7);
writeln("R: " <& rankine(kelvin) digits 2 lpad 7);
end func;</lang>
end func;</syntaxhighlight>


{{out}}
{{out}}
Line 4,342: Line 5,044:
=={{header|Sidef}}==
=={{header|Sidef}}==
{{trans|Perl}}
{{trans|Perl}}
<lang ruby>var scale = Hash(
<syntaxhighlight lang="ruby">var scale = Hash(
Celcius => Hash.new(factor => 1 , offset => -273.15 ),
Celcius => Hash.new(factor => 1 , offset => -273.15 ),
Rankine => Hash.new(factor => 1.8, offset => 0 ),
Rankine => Hash.new(factor => 1.8, offset => 0 ),
Line 4,353: Line 5,055:
scale.keys.sort.each { |key|
scale.keys.sort.each { |key|
printf("%12s:%8.2f\n", key, kelvin*scale{key}{:factor} + scale{key}{:offset});
printf("%12s:%8.2f\n", key, kelvin*scale{key}{:factor} + scale{key}{:offset});
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 4,364: Line 5,066:
=={{header|Swift}}==
=={{header|Swift}}==


<lang swift>
<syntaxhighlight lang="swift">
func KtoC(kelvin : Double)->Double{
func KtoC(kelvin : Double)->Double{
Line 4,388: Line 5,090:
var r=KtoR(kelvin : k)
var r=KtoR(kelvin : k)
print("\(r) Rankine")
print("\(r) Rankine")
</syntaxhighlight>
</lang>


=={{header|Tcl}}==
=={{header|Tcl}}==
<lang tcl>proc temps {k} {
<syntaxhighlight lang="tcl">proc temps {k} {
set c [expr {$k - 273.15}]
set c [expr {$k - 273.15}]
set r [expr {$k / 5.0 * 9.0}]
set r [expr {$k / 5.0 * 9.0}]
set f [expr {$r - 459.67}]
set f [expr {$r - 459.67}]
list $k $c $f $r
list $k $c $f $r
}</lang>
}</syntaxhighlight>




Demonstrating:
Demonstrating:
<lang tcl>puts -nonewline "Enter a temperature in K: "
<syntaxhighlight lang="tcl">puts -nonewline "Enter a temperature in K: "
flush stdout
flush stdout
lassign [temps [gets stdin]] k c f r
lassign [temps [gets stdin]] k c f r
Line 4,406: Line 5,108:
puts [format "C: %.2f" $c]
puts [format "C: %.2f" $c]
puts [format "F: %.2f" $f]
puts [format "F: %.2f" $f]
puts [format "R: %.2f" $r]</lang>
puts [format "R: %.2f" $r]</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 4,418: Line 5,120:
=={{header|UNIX Shell}}==
=={{header|UNIX Shell}}==


==={{header|Korn Shell}}===
==={{header|ksh}}===
<syntaxhighlight lang="ksh">#!/bin/ksh
{{works with|ksh}}
<lang bash>#!/bin/ksh
# Temperature conversion
# Temperature conversion
typeset tt[1]=0.00 tt[2]=273.15 tt[3]=373.15
set -A tt 0.00 273.15 373.15
for i in {1..3}
for t in "${tt[@]}"
do
do
((t=tt[i]))
echo
echo $i
echo "Kelvin: $t K"
echo "Kelvin: $t K"
echo "Celsius: $((t-273.15)) C"
echo "Celsius: $((t-273.15)) C"
echo "Fahrenheit: $((t*18/10-459.67)) F"
echo "Fahrenheit: $((t*18/10-459.67)) F"
echo "Rankine: $((t*18/10)) R"
echo "Rankine: $((t*18/10)) R"
done</lang>
done</syntaxhighlight>


==={{header|bash}}===
==={{header|bash}}===
{{works with|Bourne Again SHell}}
{{works with|Bourne Again SHell}}
<lang bash>#!/bin/bash
<syntaxhighlight lang="bash">#!/bin/bash
# Temperature conversion
# Temperature conversion
tt[1]=0.00; tt[2]=273.15; tt[3]=373.15
tt[1]=0.00; tt[2]=273.15; tt[3]=373.15
Line 4,446: Line 5,146:
echo "Fahrenheit: $(bc<<<"scale=2;$t*18/10-459.67") F"
echo "Fahrenheit: $(bc<<<"scale=2;$t*18/10-459.67") F"
echo "Rankine: $(bc<<<"scale=2;$t*18/10") R"
echo "Rankine: $(bc<<<"scale=2;$t*18/10") R"
done</lang>
done</syntaxhighlight>


=={{header|Ursa}}==
=={{header|Ursa}}==
<lang ursa>decl double k
<syntaxhighlight lang="ursa">decl double k
while true
while true
out "Temp. in Kelvin? " console
out "Temp. in Kelvin? " console
Line 4,455: Line 5,155:
out "K\t" k endl "C\t" (- k 273.15) endl console
out "K\t" k endl "C\t" (- k 273.15) endl console
out "F\t" (- (* k 1.8) 459.67) endl "R\t" (* k 1.8) endl endl console
out "F\t" (- (* k 1.8) 459.67) endl "R\t" (* k 1.8) endl endl console
end while</lang>
end while</syntaxhighlight>


=={{header|VBA}}==
=={{header|VBA}}==


<syntaxhighlight lang="vb">
<lang vb>
Option Explicit
Option Explicit


Line 4,484: Line 5,184:
End Select
End Select
End Function
End Function
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>Input in Kelvin : 21,00
<pre>Input in Kelvin : 21,00
Line 4,493: Line 5,193:


=={{header|VBScript}}==
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
<lang vb>
WScript.StdOut.Write "Enter the temperature in Kelvin:"
WScript.StdOut.Write "Enter the temperature in Kelvin:"
tmp = WScript.StdIn.ReadLine
tmp = WScript.StdIn.ReadLine
Line 4,513: Line 5,213:
rankine = (k-273.15)*1.8+491.67
rankine = (k-273.15)*1.8+491.67
End Function
End Function
</syntaxhighlight>
</lang>


{{Out}}
{{Out}}
Line 4,526: Line 5,226:


=={{header|Visual FoxPro}}==
=={{header|Visual FoxPro}}==
<lang vfp>#DEFINE ABSZC 273.16
<syntaxhighlight lang="vfp">#DEFINE ABSZC 273.16
#DEFINE ABSZF 459.67
#DEFINE ABSZF 459.67
LOCAL k As Double, c As Double, f As Double, r As Double, n As Integer, ;
LOCAL k As Double, c As Double, f As Double, r As Double, n As Integer, ;
Line 4,550: Line 5,250:
ENDDO
ENDDO
SET FIXED &cf
SET FIXED &cf
SET DECIMALS TO n</lang>
SET DECIMALS TO n</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 4,557: Line 5,257:
F: -421.87
F: -421.87
R: 37.80
R: 37.80
</pre>

=={{header|V (Vlang)}}==
Note: round_sig in 0.3 or later
<syntaxhighlight lang="v (vlang)">import math

fn main() {
c, f, r := kelvin_to_cfr(21)
println('Celsius: $c˚\nFahrenheit: $f˚\nRankine: $r˚')
}

fn kelvin_to_cfr(kelvin f64) (string, string, string) {
celsius := math.round_sig(kelvin - 273.15, 2)
fahrenheit := math.round_sig(kelvin * 1.8 - 459.67, 2)
rankine := math.round_sig(kelvin * 1.8, 2)
return celsius.str(), fahrenheit.str(), rankine.str()
}</syntaxhighlight>

{{out}}
<pre>
Celsius: -252.15˚
Fahrenheit: -421.87˚
Rankine: 38.80˚
</pre>
</pre>


=={{header|Wren}}==
=={{header|Wren}}==
{{libheader|Wren-fmt}}
{{libheader|Wren-fmt}}
<lang ecmascript>import "/fmt" for Fmt
<syntaxhighlight lang="wren">import "./fmt" for Fmt


var tempConv = Fn.new { |k|
var tempConv = Fn.new { |k|
Line 4,575: Line 5,298:


var ks = [0, 21, 100]
var ks = [0, 21, 100]
for (k in ks) tempConv.call(k)</lang>
for (k in ks) tempConv.call(k)</syntaxhighlight>


{{out}}
{{out}}
Line 4,596: Line 5,319:


=={{header|XLISP}}==
=={{header|XLISP}}==
<lang xlisp>(DEFUN CONVERT-TEMPERATURE ()
<syntaxhighlight lang="xlisp">(DEFUN CONVERT-TEMPERATURE ()
(SETQ *FLONUM-FORMAT* "%.2f")
(SETQ *FLONUM-FORMAT* "%.2f")
(DISPLAY "Enter a temperature in Kelvin.")
(DISPLAY "Enter a temperature in Kelvin.")
Line 4,608: Line 5,331:
(DISPLAY `(F = ,(- (* K 1.8) 459.67)))
(DISPLAY `(F = ,(- (* K 1.8) 459.67)))
(NEWLINE)
(NEWLINE)
(DISPLAY `(R = ,(* K 1.8))))</lang>
(DISPLAY `(R = ,(* K 1.8))))</syntaxhighlight>
{{out}}
{{out}}
<pre>(CONVERT-TEMPERATURE)
<pre>(CONVERT-TEMPERATURE)
Line 4,619: Line 5,342:


=={{header|XPL0}}==
=={{header|XPL0}}==
<lang XPL0>include c:\cxpl\codes;
<syntaxhighlight lang="xpl0">include c:\cxpl\codes;
real K, C, F, R;
real K, C, F, R;
[ChOut(0, ^K); K:= RlIn(0);
[ChOut(0, ^K); K:= RlIn(0);
Line 4,628: Line 5,351:
R:= F + 459.67;
R:= F + 459.67;
ChOut(0, ^R); RlOut(0, R); CrLf(0);
ChOut(0, ^R); RlOut(0, R); CrLf(0);
]</lang>
]</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>K 21
K 21
C -252.15000
C -252.15000
F -421.87000
F -421.87000
R 37.80000
R 37.80000</pre>
</pre>


=={{header|zkl}}==
=={{header|zkl}}==
<lang zkl>K:=ask(0,"Kelvin: ").toFloat();
<syntaxhighlight lang="zkl">K:=ask(0,"Kelvin: ").toFloat();
println("K %.2f".fmt(K));
println("K %.2f".fmt(K));
println("F %.2f".fmt(K*1.8 - 459.67));
println("F %.2f".fmt(K*1.8 - 459.67));
println("C %.2f".fmt(K - 273.15));
println("C %.2f".fmt(K - 273.15));
println("R %.2f".fmt(K*1.8));</lang>
println("R %.2f".fmt(K*1.8));</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>Kelvin: 373.15
Kelvin: 373.15
K 373.15
K 373.15
F 212.00
F 212.00
C 100.00
C 100.00
R 671.67
R 671.67</pre>
</pre>

=={{header|ZX Spectrum Basic}}==

<lang zxbasic>10 REM Translation of traditional basic version
20 INPUT "Kelvin Degrees? ";k
30 IF k <= 0 THEN STOP: REM A value of zero or less will end program
40 LET c = k - 273.15
50 LET f = k * 1.8 - 459.67
60 LET r = k * 1.8
70 PRINT k; " Kelvin is equivalent to"
80 PRINT c; " Degrees Celsius"
90 PRINT f; " Degrees Fahrenheit"
100 PRINT r; " Degrees Rankine"
110 GO TO 20</lang>

Latest revision as of 23:01, 20 March 2024

Task
Temperature conversion
You are encouraged to solve this task according to the task description, using any language you may know.

There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones: Kelvin, Celsius, Fahrenheit, and Rankine.

The Celsius and Kelvin scales have the same magnitude, but different null points.

0 degrees Celsius corresponds to 273.15 kelvin.
0 kelvin is absolute zero.

The Fahrenheit and Rankine scales also have the same magnitude, but different null points.

0 degrees Fahrenheit corresponds to 459.67 degrees Rankine.
0 degrees Rankine is absolute zero.

The Celsius/Kelvin and Fahrenheit/Rankine scales have a ratio of 5 : 9.


Task

Write code that accepts a value of kelvin, converts it to values of the three other scales, and prints the result.


Example
K  21.00

C  -252.15

F  -421.87

R  37.80



11l

V k = 21.0
print(‘K  ’k)
print(‘C  ’(k - 273.15))
print(‘F  ’(k * 1.8 - 459.67))
print(‘R  ’(k * 1.8))
Output:
K  21
C  -252.15
F  -421.87
R  37.8

360 Assembly

Translation of: AWK

Use of packed decimal arithmetic (ZAP,SP,MP,DP,UNPK,CVD,EDMK opcodes).

*        Temperature conversion    10/09/2015
TEMPERAT CSECT
         USING  TEMPERAT,R15
         LA     R4,1               i=1
         LA     R5,TT              @tt(1)
         LA     R6,IDE             @ide(1)
LOOPI    CH     R4,=AL2((T-TT)/8)  do i=1 to hbound(tt)
         BH     ELOOPI
         ZAP    T,0(8,R5)          t=tt(i)
         CVD    R4,DW              store to packed decimal
         UNPK   PG(1),DW+7(1)      unpack
         OI     PG,X'F0'           zap sign
         MVI    PG+1,C' '
         MVC    PG+2(12),0(R6)     ide(i)
         XPRNT  PG,14              output i
         MVC    PG(12),=C'Kelvin:     '
         MVC    ZN,EDMASKN         load mask
         EDMK   ZN,T+5             t (PL3)
         BCTR   R1,0               sign location
         MVC    0(1,R1),ZN+L'ZN-1  put sign
         MVC    PG+12(L'ZN-1),ZN   value
         MVC    PG+19(2),=C' K'    unit
         XPRNT  PG,21              output Kelvin
         MVC    PG(12),=C'Celsius:    '
         ZAP    DW,T               t
         SP     DW,=P'273.15'      t-273.15
         MVC    ZN,EDMASKN         load mask
         EDMK   ZN,DW+5            (PL3)
         BCTR   R1,0               sign location
         MVC    0(1,R1),ZN+L'ZN-1  put sign
         MVC    PG+12(L'ZN-1),ZN   value
         MVC    PG+19(2),=C' C'    unit
         XPRNT  PG,21              output Celsius
         MVC    PG(12),=C'Fahrenheit: '
         ZAP    DW,T               t
         MP     DW,=P'18'          *18
         DP     DW,=PL3'10'        /10
         ZAP    DW,DW(5)
         SP     DW,=P'459.67'      t*1.8-459.67
         MVC    ZN,EDMASKN         load mask
         EDMK   ZN,DW+5            (PL3)
         BCTR   R1,0               sign location
         MVC    0(1,R1),ZN+L'ZN-1  put sign
         MVC    PG+12(L'ZN-1),ZN   value
         MVC    PG+19(2),=C' F'    unit
         XPRNT  PG,21              output Fahrenheit
         MVC    PG(12),=C'Rankine:    '
         ZAP    DW,T               t
         MP     DW,=P'18'          *18
         DP     DW,=PL3'10'        /10
         ZAP    DW,DW(5)           t*1.8
         MVC    ZN,EDMASKN         load mask
         EDMK   ZN,DW+5            (PL3)
         BCTR   R1,0               sign location
         MVC    0(1,R1),ZN+L'ZN-1  put sign
         MVC    PG+12(L'ZN-1),ZN   value
         MVC    PG+19(2),=C' R'    unit
         XPRNT  PG,21              output Rankine
         LA     R4,1(R4)           i=i+1
         LA     R5,8(R5)           @tt(i)
         LA     R6,12(R6)          @ide(i)
         B      LOOPI
ELOOPI   XR     R15,R15
         BR     R14
IDE      DC     CL12'absolute',CL12'ice melts',CL12'water boils'
TT       DC     PL8'0.00',PL8'273.15',PL8'373.15'
T        DS     PL8
PG       DS     CL24
ZN       DS     ZL8                5num
DW       DS     D                  PL8 15num
EDMASKN  DC     X'402021204B202060'     CL8 5num
         YREGS
         END    TEMPERAT
Output:
1 absolute
Kelvin:        0.00 K
Celsius:    -273.15 C
Fahrenheit: -459.67 F
Rankine:       0.00 R
2 ice melts
Kelvin:      273.15 K
Celsius:       0.00 C
Fahrenheit:   32.00 F
Rankine:     491.67 R
3 water boils
Kelvin:      373.15 K
Celsius:     100.00 C
Fahrenheit:  212.00 F
Rankine:     671.67 R

8th

: KtoC \ n -- n
    273.15 n:- 
;

: KtoF \ n -- n
    1.8 n:* 459.67 n:-
;

: KtoR \ n -- n
    1.8 n:*
;

: KtoCFR \ n --
    dup dup dup
    . " degrees Kelvin" . cr
    KtoC
    . " degrees Celcius" . cr
    KtoF
    . " degrees Fahrenheit" . cr
    KtoR
    . " degrees Rankine" . cr
;

: app:main \ 
    argc 0 n:= 
    if
        "Syntax" . cr "    temp.8th number" . cr
    else
        0 args >n KtoCFR 
    then 
    bye
;
Output:
>8th temp.8th 21
21 degrees Kelvin
-252.15000 degrees Celcius
-421.87000 degrees Fahrenheit
37.80000 degrees Rankine

Action!

INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit

PROC K2C(REAL POINTER k,c)
  REAL tmp

  ValR("273.15",tmp)
  RealSub(k,tmp,c)
RETURN

PROC K2F(REAL POINTER k,f)
  REAL tmp1,tmp2,tmp3

  ValR("1.8",tmp1)
  ValR("459.67",tmp2)
  RealMult(k,tmp1,tmp3)
  RealSub(tmp3,tmp2,f)
RETURN

PROC K2R(REAL POINTER k,f)
  REAL tmp

  ValR("1.8",tmp)
  RealMult(k,tmp,f)
RETURN

PROC Test(CHAR ARRAY text REAL POINTER k)
  REAL res

  PrintE(text)
  Print("      Kelvin: ") PrintRE(k)

  K2C(k,res)
  Print("     Celsius: ") PrintRE(res)

  K2F(k,res)
  Print("  Fahrenheit: ") PrintRE(res)

  K2R(k,res)
  Print("     Rankine: ") PrintRE(res)

  PutE()
RETURN

PROC Main()
  REAL k
  
  Put(125) PutE() ;clear screen

  ValR("0",k) Test("Absolute zero",k)
  ValR("273.15",k) Test("Ice melts",k)
  ValR("373.15",k) Test("Water boils",k)
RETURN
Output:

Screenshot from Atari 8-bit computer

Absolute zero
      Kelvin: 0
     Celsius: -273.15
  Fahrenheit: -459.67
     Rankine: 0

Ice melts
      Kelvin: 273.15
     Celsius: 0
  Fahrenheit: 32
     Rankine: 491.67

Water boils
      Kelvin: 373.15
     Celsius: 100
  Fahrenheit: 212
     Rankine: 671.67

Ada

with Ada.Float_Text_IO, Ada.Text_IO;  use Ada.Float_Text_IO, Ada.Text_IO;

procedure Temperatur_Conversion is
   K: Float;
   function C return Float is (K - 273.15);
   function F return Float is (K * 1.8 - 459.67);
   function R return Float is (K * 1.8);
begin
   Get(K); New_Line;                                           -- Format 
   Put("K: "); Put(K, Fore => 4, Aft => 2, Exp => 0); New_Line;-- K: dddd.dd
   Put("C: "); Put(C, Fore => 4, Aft => 2, Exp => 0); New_Line;-- C: dddd.dd
   Put("F: "); Put(F, Fore => 4, Aft => 2, Exp => 0); New_Line;-- F: dddd.dd
   Put("R: "); Put(R, Fore => 4, Aft => 2, Exp => 0); New_Line;-- R: dddd.dd
end;
Output:
21.0

K:   21.00
C: -252.15
F: -421.87
R:   37.80

Aime

void
show(integer symbol, real temperature)
{
    o_form("%c /d2p2w8/\n", symbol, temperature);
}

integer
main(void)
{
    real k;

    k = atof(argv(1));

    show('K', k);
    show('C', k - 273.15);
    show('F', k * 1.8 - 459.67);
    show('R', k * 1.8);

    return 0;
}
Output:
aime$ aime -a tmp/tconvert 300
K   300   
C    26.85
F    80.32
R   540

ALGOL 68

BEGIN
   REAL kelvin;
   read (kelvin);
   FORMAT f = $g(8,2), " K = ", g(8,2)xgl$;
   printf ((f, kelvin, kelvin - 273.15, "C"));
   printf ((f, kelvin, 9.0 * kelvin / 5.0, "R"));
   printf ((f, kelvin, 9.0 * kelvin / 5.0 - 459.67, "F"))
END
Output:
$ echo 21 | a68g Temperature_conversion.a68
  +21.00 K =  -252.15 C
  +21.00 K =   +37.80 R
  +21.00 K =  -421.87 F
$ 

ALGOL-M

If the temperature in Kelvin is a whole number, you should type a decimal point after it (e.g. 290.): 290 with no decimal point will be interpreted as 0.29 rather than 290.0.

BEGIN
    DECIMAL K, C, F, R;
    WRITE( "Temperature in Kelvin:" );
    READ( K );
    C := K - 273.15;
    F := K * 1.8 - 459.67;
    R := K * 1.8;
    WRITE( K, " Kelvin is equivalent to" );
    WRITE( C, " degrees Celsius" );
    WRITE( F, " degrees Fahrenheit" );
    WRITE( R, " degrees Rankine" );
END

ALGOL W

begin % convert Kelvin to Celcius, Farenheit and Rankine                      %
    real kelvin, rankine;
    write( "Kelvin: " );
    read( kelvin );
    rankine := ( 9 * kelvin ) / 5;
    r_format := "A"; r_w := 8; r_d := 2; s_w := 0;     % set output formating %
    write( kelvin, " Kelvin is:" );
    write( "    ", kelvin  - 273.15, " Celcius"   );
    write( "    ", rankine,          " Rankine"   );
    write( "    ", rankine - 459.67, " Farenheit" )
end.

Amazing Hopper

/* MISTRAL - a flavour of Hopper */

#include <mistral.h>

INICIAR:
   TAMAÑO DE MEMORIA 20
   temperatura=0
   RECIBIR PARÁMETRO NUMÉRICO(2), GUARDAR EN (temperatura); 
   TOMAR("KELVIN     : ",temperatura, NL)
   CON( "CELSIUS    : ", temperatura ), CALCULAR( Conversión Kelvin a Celsius ),    NUEVA LÍNEA
   CON( "FAHRENHEIT : ", temperatura ), CALCULAR( Conversión Kelvin a Fahrenheit ), NUEVA LÍNEA
   CON( "RANKINE    : ", temperatura ), CALCULAR( Conversión Kelvin a Rankine ),    NUEVA LÍNEA
   IMPRIMIR CON SALTO
FINALIZAR

SUBRUTINAS

FUNCIÓN(Conversión Kelvin a Celsius, k)
    REDONDEAR(RESTAR(k, 273.15), 2)
RETORNAR

FUNCIÓN( Conversión Kelvin a Fahrenheit, k)
    REDONDEAR( {k} MULTIPLICADO POR(1.8) MENOS( 459.67), 2)
RETORNAR

FUNCIÓN( Conversión Kelvin a Rankine, k)
RETORNAR ( {k} POR (1.8), REDONDEADO AL DECIMAL(2) )

Another version:

/* MISTRAL - a flavour of Hopper */

#include <mistral.h>

INICIAR:
   temperatura=0
   RECIBIR PARÁMETRO NUMÉRICO(2), GUARDAR EN (temperatura); 
   IMPRIMIR("KELVIN     : ",temperatura, NL)
   IMPRIMIR("CELSIUS    : ",temperatura, MENOS '273.15', NL) 
   IMPRIMIR("FAHRENHEIT : ",temperatura, POR '1.8' MENOS '459.67', NL)
   IMPRIMIR("RANKINE    : ",temperatura, POR '1.8', NL)
FINALIZAR

Another version:

#include <mistral.h>

INICIAR:
   TAMAÑO DE MEMORIA 15
   temperatura=0
   RECIBIR PARÁMETRO NUMÉRICO(2), GUARDAR EN (temperatura); 
   IMPRIMIR("KELVIN     : ", temperatura, NL,\
            "CELSIUS    : ", {temperatura} MENOS '273.15', NL,\ 
            "FAHRENHEIT : ", {temperatura} POR '1.8' MENOS '459.67', NL,\
            "RANKINE    : ", {temperatura} POR '1.8', NL)
FINALIZAR

Or another (and last) version:

#include <mistral.h>

INICIAR:
   TAMAÑO DE MEMORIA 20
   temperatura=0, rankine=0
   RECIBIR PARÁMETRO NUMÉRICO(2), GUARDAR EN (temperatura); 
   IMPRIMIR("KELVIN     : ", temperatura, NL,\
            "CELSIUS    : ", {temperatura} MENOS '273.15', NL,\ 
            "FAHRENHEIT : ", {temperatura} POR '1.8' ---RESPALDE EN 'rankine'--- MENOS '459.67', NL,\
            "RANKINE    : ", rankine, NL)
FINALIZAR
Output:
$ hopper conv.mistral 0
KELVIN     : 0
CELSIUS    : -273.15
FAHRENHEIT : -459.67
RANKINE    : 0
$ hopper conv.mistral 21
KELVIN     : 21
CELSIUS    : -252.15
FAHRENHEIT : -421.87
RANKINE    : 37.8

APL

Given a temperature in Kelvin, prints the equivalent in Kelvin, Celsius, Fahrenheit, and Rankine (in that order).

      CONVERT{,(-273.15),(R-459.67),(R×9÷5)}
Output:
      CONVERT 21
21 ¯252.15 ¯421.87 37.8

The "high minus" character ¯ is used in APL to mark negative numbers, preventing any possible confusion with - (the subtraction operator).

AppleScript

Translation of: JavaScript

( ES6 version )

use framework "Foundation" -- Yosemite onwards, for the toLowerCase() function

-- KELVIN TO OTHER SCALE -----------------------------------------------------

-- kelvinAs :: ScaleName -> Num -> Num
on kelvinAs(strOtherScale, n)
    heatBabel(n, "Kelvin", strOtherScale)
end kelvinAs

-- MORE GENERAL CONVERSION ---------------------------------------------------

-- heatBabel :: n -> ScaleName -> ScaleName -> Num
on heatBabel(n, strFromScale, strToScale)
    set ratio to 9 / 5
    set cels to 273.15
    set fahr to 459.67
    
    script reading
        on |λ|(x, strFrom)
            if strFrom = "k" then
                x as real
            else if strFrom = "c" then
                x + cels
            else if strFrom = "f" then
                (fahr + x) * ratio
            else
                x / ratio
            end if
        end |λ|
    end script
    
    script writing
        on |λ|(x, strTo)
            if strTo = "k" then
                x
            else if strTo = "c" then
                x - cels
            else if strTo = "f" then
                (x * ratio) - fahr
            else
                x * ratio
            end if
        end |λ|
    end script
    
    writing's |λ|(reading's |λ|(n, ¬
        toLower(text 1 of strFromScale)), ¬
        toLower(text 1 of strToScale))
end heatBabel


-- TEST ----------------------------------------------------------------------
on kelvinTranslations(n)
    script translations
        on |λ|(x)
            {x, kelvinAs(x, n)}
        end |λ|
    end script
    
    map(translations, {"K", "C", "F", "R"})
end kelvinTranslations

on run
    script tabbed
        on |λ|(x)
            intercalate(tab, x)
        end |λ|
    end script
    
    intercalate(linefeed, map(tabbed, kelvinTranslations(21)))
end run


-- GENERIC FUNCTIONS ---------------------------------------------------------

-- intercalate :: Text -> [Text] -> Text
on intercalate(strText, lstText)
    set {dlm, my text item delimiters} to {my text item delimiters, strText}
    set strJoined to lstText as text
    set my text item delimiters to dlm
    return strJoined
end intercalate

-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
    tell mReturn(f)
        set lng to length of xs
        set lst to {}
        repeat with i from 1 to lng
            set end of lst to |λ|(item i of xs, i, xs)
        end repeat
        return lst
    end tell
end map

-- Lift 2nd class handler function into 1st class script wrapper 
-- mReturn :: Handler -> Script
on mReturn(f)
    if class of f is script then
        f
    else
        script
            property |λ| : f
        end script
    end if
end mReturn

-- toLower :: String -> String
on toLower(str)
    set ca to current application
    ((ca's NSString's stringWithString:(str))'s ¬
        lowercaseStringWithLocale:(ca's NSLocale's currentLocale())) as text
end toLower
Output:
K    21.0
C    -252.15
F    -421.87
R    37.8

Or of course:

on convertFromKelvin(kelvinValue)
    return ("K" & tab & (kelvinValue as real)) & ¬
        (linefeed & "C" & tab & (kelvinValue - 273.15)) & ¬
        (linefeed & "F" & tab & ((kelvinValue - 273.15) * 9 / 5 + 32)) & ¬
        (linefeed & "R" & tab & (kelvinValue * 9 / 5))
end convertFromKelvin

convertFromKelvin(21)

Vanilla AppleScript actually has a handful of built-in measurement unit coercions, including three for converting between temperatures in Kelvin, Celsius, and Fahrenheit. There isn't one for Rankine, but it's an easy calculation from Kelvin:

on convertFromKelvin(kelvinValue)
    set kelvinMeasurement to kelvinValue as degrees Kelvin
    
    set celsiusValue to kelvinMeasurement as degrees Celsius as number
    set fahrenheitValue to kelvinMeasurement as degrees Fahrenheit as number
    set rankineValue to kelvinValue * 9 / 5
    
    return ("K" & tab & (kelvinValue as real)) & ¬
        (linefeed & "C" & tab & celsiusValue) & ¬
        (linefeed & "F" & tab & fahrenheitValue) & ¬
        (linefeed & "R" & tab & rankineValue)
end convertFromKelvin

convertFromKelvin(21)

As from macOS 10.12 Sierra, macOS's Foundation framework too offers "Units and Measurement" classes and methods, which can be accessed from AppleScript using ASObjC code. They offer many more categories and units, although it's usually easier, faster, and more efficient (and occasionally more accurate!) to look up the conversion formulae on Wikipedia and write the math directly into the scripts, as above.

use AppleScript version "2.5" -- macOS 10.12 (Sierra) or later
use framework "Foundation"

on convertFromKelvin(kelvinValue)
    set |⌘| to current application
    
    -- Set up an NSMeasurement object representing the given number of Kelvin units.
    set kelvinUnit to |⌘|'s class "NSUnitTemperature"'s kelvin()
    set kelvinMeasurement to |⌘|'s class "NSMeasurement"'s alloc()'s initWithDoubleValue:(kelvinValue) unit:(kelvinUnit)
    
    -- Get value of the same measurement in each of the other "units" in turn.
    set celsiusUnit to |⌘|'s class "NSUnitTemperature"'s celsius()
    set celsiusMeasurement to kelvinMeasurement's measurementByConvertingToUnit:(celsiusUnit)
    set celsiusValue to celsiusMeasurement's doubleValue()
    
    set fahrenheitUnit to |⌘|'s class "NSUnitTemperature"'s fahrenheit()
    set fahrenheitMeasurement to kelvinMeasurement's measurementByConvertingToUnit:(fahrenheitUnit)
    set fahrenheitValue to fahrenheitMeasurement's doubleValue()
    
    -- There's no predefined unit for Rankine (as at macOS 10.14 Mojave), but custom units are easy to define.
    -- A unit's linear 'converter' must contain the unit's size and zero offset relative to those of its class's "base unit"
    -- which for temperatures is the 'kelvin' unit.
    set rankineConverter to |⌘|'s class "NSUnitConverterLinear"'s alloc()'s initWithCoefficient:(5 / 9) |constant|:(0)
    set rankineUnit to |⌘|'s class "NSUnitTemperature"'s alloc()'s initWithSymbol:("°R") converter:(rankineConverter)
    set rankineMeasurement to kelvinMeasurement's measurementByConvertingToUnit:(rankineUnit)
    set rankineValue to rankineMeasurement's doubleValue()
    
    return ("K" & tab & (kelvinValue as real)) & ¬
        (linefeed & "C" & tab & celsiusValue) & ¬
        (linefeed & "F" & tab & fahrenheitValue) & ¬
        (linefeed & "R" & tab & rankineValue)
end convertFromKelvin

convertFromKelvin(21)

Arturo

convertKelvins: function [k][
    #[
        celcius:    k - 273.15
        fahrenheit: (k * 9/5.0)-459.67
        rankine:    k * 9/5.0
    ]
]

print convertKelvins 100
Output:
[celcius:-173.15 fahrenheit:-279.67 rankine:180.0]

Asymptote

void convKelvin(real K) {
    write("K = " + string(K));
    write("C = " + string(K - 273.15));
    write("F = " + string((K - 273.15) * 1.8 + 32.0));
    write("R = " + string(K * 1.8));
}

convKelvin(0.0);
write("");
convKelvin(21.0);

AutoHotkey

MsgBox, % "Kelvin:`t`t 21.00 K`n"
        . "Celsius:`t`t" kelvinToCelsius(21) " C`n"
        . "Fahrenheit:`t" kelvinToFahrenheit(21) " F`n"
        . "Rankine:`t`t" kelvinToRankine(21) " R`n"

kelvinToCelsius(k)
{
    return, round(k - 273.15, 2)
}
kelvinToFahrenheit(k)
{
    return, round(k * 1.8 - 459.67, 2)
}
kelvinToRankine(k)
{
    return, round(k * 1.8, 2)
}
Output:
Kelvin:          21.00 K
Celsius:       -252.15 C
Fahrenheit:    -421.87 F
Rankine:         37.80 R

AutoIt

;  ### USAGE - TESTING PURPOSES ONLY

Local Const $_KELVIN = 21
ConsoleWrite("Kelvin: " & $_KELVIN & @CRLF)
ConsoleWrite("Kelvin: " & Kelvin(21, "C") & @CRLF)
ConsoleWrite("Kelvin: " & Kelvin(21, "F") & @CRLF)
ConsoleWrite("Kelvin: " & Kelvin(21, "R") & @CRLF)

;   ### KELVIN TEMPERATURE CONVERSIONS

Func Kelvin($degrees, $conversion)
    Select
        Case $conversion = "C"
            Return Round($degrees - 273.15, 2)
        Case $conversion = "F"
            Return Round(($degrees * 1.8) - 459.67, 2)
        Case $conversion = "R"
            Return Round($degrees * 1.8, 2)
    EndSelect
EndFunc ;==> Kelvin
Output:
Kelvin: 21°
Celsius: -252.15°
Fahrenheit: -421.87°
Rankine: 37.8°

AWK

"Interactive" version, reading from stdin only:

# syntax: AWK -f TEMPERATURE_CONVERSION.AWK
BEGIN {
    while (1) {
      printf("\nKelvin degrees? ")
      getline K
      if (K ~ /^$/) {
        break
      }
      if (K < 0) {
        print("K must be >= 0")
        continue
      }
      printf("K = %.2f\n",K)
      printf("C = %.2f\n",K - 273.15)
      printf("F = %.2f\n",K * 1.8 - 459.67)
      printf("R = %.2f\n",K * 1.8)
    }
    exit(0)
}

"Regular" version, reading from input-file(s).
With no such file, or "-" as filename, reading from stdin:

Works with: gawk

BEGINFILE is a gawk-extension

# usage: gawk -f temperature_conversion.awk  input.txt -

BEGIN     { print("# Temperature conversion\n") }
BEGINFILE { print "# reading", FILENAME
            if( FILENAME=="-" ) print "# Please enter temperature values in K:\n"
          }

!NF       { exit }

          { print "Input:" $0 }     
$1<0      { print("K must be >= 0\n"); next }
          { K = 0+$1
            printf("K = %8.2f Kelvin degrees\n",K)
            printf("C = %8.2f\n",  K - 273.15)
            printf("F = %8.2f\n",  K * 1.8 - 459.67)
            printf("R = %8.2f\n\n",K * 1.8)
          }

END       { print("# Bye.") }
Input:

the numeric value of the first word in each line is used as input for the conversion

-1
absolute
184
273.15 ice melts
310x
373.15 water boils
1941 Titanium melts

So, "absolute" has a value of 0, and 310x is just 310.

After that file is read and processed, values are read from stdin.
Here entering "333" by hand, and then stopping with an empty input.

Output:
# Temperature conversion

# reading input.txt
Input:-1
K must be >= 0

Input:absolute
K =     0.00 Kelvin degrees
C =  -273.15
F =  -459.67
R =     0.00

Input:184
K =   184.00 Kelvin degrees
C =   -89.15
F =  -128.47
R =   331.20

Input:273.15 ice melts
K =   273.15 Kelvin degrees
C =     0.00
F =    32.00
R =   491.67

Input:310x
K =   310.00 Kelvin degrees
C =    36.85
F =    98.33
R =   558.00

Input:373.15 water boils
K =   373.15 Kelvin degrees
C =   100.00
F =   212.00
R =   671.67

Input:1941 Titanium melts
K =  1941.00 Kelvin degrees
C =  1667.85
F =  3034.13
R =  3493.80

# reading -
# Please enter temperature values in K:

Input:333
K =   333.00 Kelvin degrees
C =    59.85
F =   139.73
R =   599.40

# Bye.

BASIC

10 REM TRANSLATION OF AWK VERSION
20 INPUT "KELVIN DEGREES",K
30 IF K <= 0 THEN END: REM A VALUE OF ZERO OR LESS WILL END PROGRAM
40 LET C = K - 273.15
50 LET F = K * 1.8 - 459.67
60 LET R = K * 1.8
70 PRINT K; " KELVIN IS EQUIVALENT TO"
80 PRINT C; " DEGREES CELSIUS"
90 PRINT F; " DEGREES FAHRENHEIT"
100 PRINT R; " DEGREES RANKINE"
110 GOTO 20

Applesoft BASIC

The Chipmunk_Basic solution works without any changes.

BASIC256

do
  print "Kelvin degrees (>=0): ";
  input K
  until K>=0

print "K = " + string(K)
print "C = " + string(K - 273.15)
print "F = " + string(K * 1.8 - 459.67)
print "R = " + string(K * 1.8)

BBC BASIC

REPEAT
  INPUT "Kelvin degrees (>=0): " K
UNTIL K>=0
@%=&20208
PRINT '"K = " K
PRINT "C = " K - 273.15
PRINT "F = " K * 1.8 - 459.67
PRINT "R = " K * 1.8
END
Output:
Kelvin degrees (>=0): 21

K =    21.00
C =  -252.15
F =  -421.87
R =    37.80

Chipmunk Basic

Works with: Chipmunk Basic version 3.6.4
Works with: QBasic
Works with: QuickBasic
Works with: Applesoft BASIC
Works with: BASICA
Works with: GW-BASIC
Works with: IS-BASIC
Works with: Minimal BASIC
Works with: MSX BASIC version any
Works with: Run BASIC
Works with: Just BASIC
Works with: Liberty BASIC
10 CLS : REM  10 HOME for Applesoft BASIC : DELETE for Minimal BASIC
20 PRINT "Kelvin Degrees "; 
30 INPUT K
40 IF K <= 0 THEN 130
50 LET C = K-273.15
60 LET F = K*1.8-459.67
70 LET R = K*1.8
80 PRINT K;" Kelvin is equivalent to"
90 PRINT C;" Degrees Celsius"
100 PRINT F;" Degrees Fahrenheit"
110 PRINT R;" Degrees Rankine"
120 GOTO 20
130 END

FreeBASIC

' FB 1.05.0 Win64

Sub convKelvin(temp As Double)
  Dim f As String = "####.##"
  Print Using f; temp;
  Print " degrees Kelvin"
  Print Using f; temp - 273.15;
  Print " degrees Celsius"
  Print Using f; (temp - 273.15) * 1.8 + 32.0;
  Print " degrees Fahreneit" 
  Print Using f; (temp - 273.15) * 1.8 + 32.0 + 459.67;
  Print " degrees Rankine"
End Sub

convKelvin(0.0) 
Print
convKelvin(21.0)
Print
Print "Press any key to quit"
Sleep
Output:
   0.00 degrees Kelvin
-273.15 degrees Celsius
-459.67 degrees Fahreneit
   0.00 degrees Rankine

  21.00 degrees Kelvin
-252.15 degrees Celsius
-421.87 degrees Fahreneit
  37.80 degrees Rankine

Gambas

Public Sub Form_Open()
Dim fKelvin As Float

fKelvin = InputBox("Enter a Kelvin value", "Kelvin converter")

Print "Kelvin =\t" & Format(Str(fKelvin), "#.00")
Print "Celsius =\t" & Format(Str(fKelvin - 273.15), "#.00")
Print "Fahrenheit =\t" & Format(Str(fKelvin * 1.8 - 459.67), "#.00")
Print "Rankine =\t" & Format(Str(fKelvin * 1.8), "#.00")

End
Output:
Kelvin =        21.00
Celsius =       -252.15
Fahrenheit =    -421.87
Rankine =       37.80

GW-BASIC

The Chipmunk_Basic solution works without any changes.

IS-BASIC

100 INPUT PROMPT "Kelvin degrees: ":K
110 PRINT K;TAB(10);"Kelvin is equivalent to"
120 PRINT K-273.15;TAB(10);"Degrees Celsius"
130 PRINT K*1.8-459.67;TAB(10);"Degrees Fahrenheit"
140 PRINT K*1.8;TAB(10);"Degrees Rankine"

Liberty BASIC

Do
   Input "Kelvin degrees (>=0): ";K
Loop Until (K >= 0)

Print "K = ";K
Print "C = ";(K - 273.15)
Print "F = ";(K * 1.8 - 459.67)
Print "R = ";(K * 1.8)
End
Output:
Kelvin degrees (>=0): 21
K = 21
C = -252.15
F = -421.87
R = 37.8

Minimal BASIC

The Chipmunk_Basic solution works without any changes.

MSX Basic

The Chipmunk_Basic solution works without any changes.

PureBasic

Procedure.d Kelvin2Celsius(tK.d)    : ProcedureReturn tK-273.15     : EndProcedure
Procedure.d Kelvin2Fahrenheit(tK.d) : ProcedureReturn tK*1.8-459.67 : EndProcedure
Procedure.d Kelvin2Rankine(tK.d)    : ProcedureReturn tK*1.8        : EndProcedure

OpenConsole()
Repeat
  Print("Temperatur Kelvin? ") : Kelvin.d = ValD(Input())
  PrintN("Conversion:")
  PrintN(#TAB$+"Celsius   "+#TAB$+RSet(StrD(Kelvin2Celsius(Kelvin),2),8,Chr(32)))
  PrintN(#TAB$+"Fahrenheit"+#TAB$+RSet(StrD(Kelvin2Fahrenheit(Kelvin),2),8,Chr(32)))
  PrintN(#TAB$+"Rankine   "+#TAB$+RSet(StrD(Kelvin2Rankine(Kelvin),2),8,Chr(32)))
  PrintN("ESC = End.")
  Repeat 
    k$=Inkey() : Delay(50) : If RawKey()=#ESC : End : EndIf
  Until RawKey()  
ForEver
Temperatur Kelvin? 21
Conversion:
        Celsius          -252.15
        Fahrenheit       -421.87
        Rankine            37.80
ESC = End.

QB64

Dim As Single Celsius, Kelvin, Fahrenheit, Rankine

Kelvin = -300
While Kelvin = -300
    Input "Please type Kelvin temperature...or -300 to quit ", Kelvin
    If Kelvin = -300 Then
        End
    Else

        Celsius = Kelvin - 273.15
        Fahrenheit = ((9 / 5) * Celsius) + 32
        Rankine = Fahrenheit + 459.67
    End If
    Print " Celsius", "Fahrenheit", "Kelvin", "Rankine  "
    Print Celsius, Fahrenheit, Kelvin, Rankine
    Kelvin = -300
Wend

QBasic

DO
	INPUT "Kelvin degrees (>=0): ", K
LOOP UNTIL K >= 0

PRINT "K = " + STR$(K)
PRINT "C = " + STR$(K - 273.15)
PRINT "F = " + STR$(K * 1.8 - 459.67)
PRINT "R = " + STR$(K * 1.8)
END

Quite BASIC

10 PRINT "Kelvin Degrees "; 
20 INPUT ""; K
30 IF K <= 0 THEN END
40 LET C = K-273.15
50 LET F = K*1.8-459.67
60 LET R = K*1.8
70 PRINT K;" Kelvin is equivalent to"
80 PRINT C;" Degrees Celsius"
90 PRINT F;" Degrees Fahrenheit"
100 PRINT R;" Degrees Rankine"
110 GOTO 10

Sinclair ZX81 BASIC

10 PRINT "ENTER A TEMPERATURE IN KELVINS"
20 INPUT K
30 PRINT K;" KELVINS ="
40 PRINT K-273.15;" DEGREES CELSIUS"
50 PRINT K*1.8-459.67;" DEGREES FAHRENHEIT"
60 PRINT K*1.8;" DEGREES RANKINE"

Tiny BASIC

PRINT "Temperature in Kelvin?"
INPUT K
LET C = K + 273
LET R = (9*K)/5
LET F = R + 460
PRINT C," Celsius"
PRINT F," Fahrenheit"
PRINT R," Rankine"

True BASIC

Works with: QBasic
DO
   PRINT "Kelvin degrees (>=0): ";
   INPUT K
LOOP UNTIL K >= 0

PRINT "K = "; STR$(K)
PRINT "C = "; STR$(K - 273.15)
PRINT "F = "; STR$(K * 1.8 - 459.67)
PRINT "R = "; STR$(K * 1.8)
END

XBasic

Works with: Windows XBasic
PROGRAM "Temperature conversion"
VERSION "0.001"

DECLARE FUNCTION Entry()

FUNCTION Entry()
  DO
    D$ = INLINE$("Kelvin degrees (>=0): ")
    K = SBYTE(D$)
  LOOP UNTIL K >= 0

  PRINT "K = " + STR$(K)
  PRINT "C = " + STR$(K - 273.15)
  PRINT "F = " + STR$(K * 1.8 - 459.67)
  PRINT "R = " + STR$(K * 1.8)

END FUNCTION
END PROGRAM

Yabasic

repeat
	input "Kelvin degrees (>=0): " K
until K >= 0

print "K = " + str$(K)
print "C = " + str$(K - 273.15)
print "F = " + str$(K * 1.8 - 459.67)
print "R = " + str$(K * 1.8)
end

ZX Spectrum Basic

10 REM Translation of traditional basic version
20 INPUT "Kelvin Degrees? ";k
30 IF k <= 0 THEN STOP: REM A value of zero or less will end program
40 LET c = k - 273.15
50 LET f = k * 1.8 - 459.67
60 LET r = k * 1.8
70 PRINT k; " Kelvin is equivalent to"
80 PRINT c; " Degrees Celsius"
90 PRINT f; " Degrees Fahrenheit"
100 PRINT r; " Degrees Rankine"
110 GO TO 20

Befunge

The temperature to convert is read from stdin. Befunge has no support for real numbers, though, so reading and writing of decimal values is done with character I/O. For the same reason, the temperature calculations use integer arithmetic to emulate fixed point. The first two lines handle the input; the second line performs the conversion calculations; and the last three handle the output.

0000>0p~>"."-:!#v_2-::0\`\9`+!#v_$1>/\:3`#v_\>\:3 \`#v_v
1#<<^0 /2++g001!<1 \+g00\+*+55\<   ^+55\-1<  ^*+55\+1<v_
"K"\-+**"!Y]"9:\"C"\--\**"^CIT"/5*9:\"F"\/5*9:\"R"\0\0<v
v/+55\+*86%+55: /+55\+*86%+55: \0/+55+5*-\1*2 p00:`\0:,<
>"."\>:55+% 68*v                       >:#,_$55+,\:!#@_^
   $_^#!:/+55\+<                       ^\" :"_<g00*95
Output:
21
K: 21.00
C: -252.15
F: -421.87
R: 37.80

Bracmat

( ( rational2fixedpoint
  =   minus fixedpointnumber number decimals
    .   !arg:(#?number.~<0:~/#?decimals)
      & ( !number:0&"0.0"
        |     ( !number:>0&
              | -1*!number:?number&"-"
              )
            : ?minus
          & !number+1/2*10^(-1*!decimals):?number
          & !minus div$(!number.1) ".":?fixedpointnumber
          &   whl
            ' ( !decimals+-1:~<0:?decimals
              &     !fixedpointnumber
                    div$(mod$(!number.1)*10:?number.1)
                : ?fixedpointnumber
              )
          & str$!fixedpointnumber
        )
  )
& ( fixedpoint2rational
  =   integerpart fractionalpart decimals
    .   @( !arg
         :   #?integerpart
             ( "." ?fractionalpart
             | &0:?fractionalpart
             )
         )
      & @(!fractionalpart:? #?fractionalpart [?decimals)
      &   !integerpart
        +   (!integerpart:<0&-1|1)
          * 10^(-1*!decimals)
          * !fractionalpart
  )
&   whl
  ' ( put$"Enter Kelvin temperature:"
    & fixedpoint2rational$(get'(,STR)):?kelvin
    & !kelvin+-27315/100:?celcius
    & (degree=.str$(chu$(x2d$b0) !arg))
    & out$(rational2fixedpoint$(!kelvin.2) K)
    & out$(rational2fixedpoint$(!celcius.2) degree$C)
    & out$(rational2fixedpoint$(!celcius*9/5+32.2) degree$F)
    & out$(rational2fixedpoint$(!kelvin*9/5.2) degree$Ra)
    & out$(rational2fixedpoint$(!celcius*4/5.2) degree$Ré)
    )
& done!
)
Output:
Enter Kelvin temperature:21.00
21.00 K
-252.15 °C
-421.87 °F
37.80 °Ra
-201.72 °Ré

C

#include <stdio.h>
#include <stdlib.h>

double kelvinToCelsius(double k){
    return k - 273.15;
}

double kelvinToFahrenheit(double k){
    return k * 1.8 - 459.67;
}

double kelvinToRankine(double k){
    return k * 1.8;
}
void convertKelvin(double kelvin) {
    printf("K %.2f\n", kelvin);
    printf("C %.2f\n", kelvinToCelsius(kelvin));
    printf("F %.2f\n", kelvinToFahrenheit(kelvin));
    printf("R %.2f", kelvinToRankine(kelvin));
}

int main(int argc, const char * argv[])
{
    if (argc > 1) {
        double kelvin = atof(argv[1]);
        convertKelvin(kelvin);
    }
    return 0;
}

C#

using System;

namespace TemperatureConversion
{
    class Program
    {
        static Func<double, double> ConvertKelvinToFahrenheit = x => (x * 1.8) - 459.67;
        static Func<double, double> ConvertKelvinToRankine = x => x * 1.8;
        static Func<double, double> ConvertKelvinToCelsius = x => x = 273.13;

        static void Main(string[] args)
        {
            Console.Write("Enter a Kelvin Temperature: ");
            string inputVal = Console.ReadLine();
            double kelvinTemp = 0f;

            if (double.TryParse(inputVal, out kelvinTemp))
            {
                Console.WriteLine(string.Format("Kelvin: {0}", kelvinTemp));
                Console.WriteLine(string.Format("Fahrenheit: {0}", ConvertKelvinToFahrenheit(kelvinTemp)));
                Console.WriteLine(string.Format("Rankine: {0}", ConvertKelvinToRankine(kelvinTemp)));
                Console.WriteLine(string.Format("Celsius: {0}", ConvertKelvinToCelsius(kelvinTemp)));
                Console.ReadKey();
            }
            else
            {
                Console.WriteLine("Invalid input value: " + inputVal);
            }
        }
    }
}
Enter a Kelvin Temperature: 21
Kelvin: 21
Fahrenheit: -421.87
Rankine: 37.8
Celsius: 273.13

C++

#include <iostream>
#include <iomanip>

//--------------------------------------------------------------------------------------------------
using namespace std;

//--------------------------------------------------------------------------------------------------
class converter
{
public:
    converter() : KTC( 273.15f ), KTDel( 3.0f / 2.0f ), KTF( 9.0f / 5.0f ), KTNew( 33.0f / 100.0f ),
          KTRank( 9.0f / 5.0f ), KTRe( 4.0f / 5.0f ), KTRom( 21.0f / 40.0f ) {}

    void convert( float kelvin )
    {
    float cel = kelvin - KTC,
          del = ( 373.15f - kelvin ) * KTDel,
          fah = kelvin * KTF - 459.67f,
          net = cel * KTNew,
          rnk = kelvin * KTRank,
          rea = cel * KTRe, 
          rom = cel * KTRom + 7.5f;

    cout << endl << left
         << "TEMPERATURES:" << endl 
         << "===============" << endl << setw( 13 )
         << "CELSIUS:" << cel << endl << setw( 13 )
         << "DELISLE:" << del << endl << setw( 13 )
         << "FAHRENHEIT:" << fah << endl << setw( 13 )
         << "KELVIN:" << kelvin << endl  << setw( 13 )
         << "NEWTON:" << net << endl << setw( 13 )
         << "RANKINE:" << rnk << endl << setw( 13 )
         << "REAUMUR:" << rea << endl << setw( 13 )
         << "ROMER:" << rom << endl << endl << endl;
    }
private:
    const float KTRank, KTC, KTF, KTRe, KTDel, KTNew, KTRom;
};
//--------------------------------------------------------------------------------------------------
int main( int argc, char* argv[] )
{
    converter con;
    float k;
    while( true )
    {
    cout << "Enter the temperature in Kelvin to convert: ";
    cin >> k;
    con.convert( k );
    system( "pause" );
    system( "cls" );
    }
    return 0;
}
//--------------------------------------------------------------------------------------------------
Output:
Enter the temperature in Kelvin to convert: 373.15

TEMPERATURES:
===============
CELSIUS:     100
DELISLE:     0
FAHRENHEIT:  212
KELVIN:      373.15
NEWTON:      33
RANKINE:     671.67
REAUMUR:     80
ROMER:       60

Ceylon

shared void run() {

    void printKelvinConversions(Float kelvin) {
        value celsius = kelvin - 273.15;
        value rankine = kelvin * 9.0 / 5.0;
        value fahrenheit = rankine - 459.67;
        
        print("Kelvin:     ``formatFloat(kelvin, 2, 2)``
               Celsius:    ``formatFloat(celsius, 2, 2)``
               Fahrenheit: ``formatFloat(fahrenheit, 2, 2)``
               Rankine:    ``formatFloat(rankine, 2, 2)``");
    }
    
    printKelvinConversions(21.0);
    
}

Clojure

Translation of: Common Lisp
(defn to-celsius [k]
  (- k 273.15))
(defn to-fahrenheit [k] 
  (- (* k 1.8) 459.67))
(defn to-rankine [k] 
  (* k 1.8))
 
(defn temperature-conversion [k] 
  (if (number? k) 
    (format "Celsius: %.2f Fahrenheit: %.2f Rankine: %.2f" 
      (to-celsius k) (to-fahrenheit k) (to-rankine k)) 
    (format "Error: Non-numeric value entered.")))
Output:
user=> (temperature-conversion 21.0)
"Celsius: -252.15 Fahrenheit: -421.87 Rankine: 37.80"

CLU

kelvin = proc (k: real) returns (real) 
    return(k) 
end kelvin 

celsius = proc (k: real) returns (real)
    return(k - 273.15)
end celsius

rankine = proc (k: real) returns (real)
    return(k * 9./5.)
end rankine

fahrenheit = proc (k: real) returns (real)
    return(rankine(k) - 459.67)
end fahrenheit

conv = struct[letter: char, func: proctype (real) returns (real)]

convs = sequence[conv]$[
    conv${letter: 'K', func: kelvin},
    conv${letter: 'C', func: celsius},
    conv${letter: 'F', func: fahrenheit},
    conv${letter: 'R', func: rankine}
]

start_up = proc ()
    pi: stream := stream$primary_input()
    po: stream := stream$primary_output()
    
    stream$puts(po, "Enter temperature in Kelvin: ")
    k: real := real$parse(stream$getl(pi))
    
    for c: conv in sequence[conv]$elements(convs) do
        stream$putc(po, c.letter)
        stream$puts(po, "  ")
        stream$putl(po, f_form(c.func(k), 6, 2))
    end
end start_up
Output:
Enter temperature in Kelvin: 21
K  21.00
C  -252.15
F  -421.87
R  37.80

COBOL

Works with: Visual COBOL
       IDENTIFICATION DIVISION.
       PROGRAM-ID. temp-conversion.
       
       DATA DIVISION.
       WORKING-STORAGE SECTION.
       78  Kelvin-Rankine-Ratio    VALUE 0.5556. *> 5 / 9 to 4 d.p.
       78  Kelvin-Celsius-Diff     VALUE 273.15.
       78  Rankine-Fahrenheit-Diff VALUE 459.67.
       
       01  temp-kelvin             PIC S9(8)V99.
       01  temp-rankine            PIC S9(8)V99.
       
       01  kelvin                  PIC -(7)9.99.
       01  celsius                 PIC -(7)9.99.
       01  rankine                 PIC -(7)9.99.
       01  fahrenheit              PIC -(7)9.99.
       
       PROCEDURE DIVISION.
           DISPLAY "Enter a temperature in Kelvin to convert: " NO ADVANCING
           ACCEPT temp-kelvin
       
           MOVE temp-kelvin TO kelvin
           DISPLAY "K " kelvin
           
           SUBTRACT Kelvin-Celsius-Diff FROM temp-kelvin GIVING celsius
           DISPLAY "C " celsius
           
           DIVIDE temp-kelvin BY Kelvin-Rankine-Ratio
               GIVING temp-rankine, rankine
           SUBTRACT Rankine-Fahrenheit-Diff FROM temp-rankine GIVING fahrenheit
           
           DISPLAY "F " fahrenheit
           DISPLAY "R " rankine
       
           GOBACK
           .
Output:
Enter a temperature in Kelvin to convert: 21
K       21.00
C     -252.15
F     -421.88
R       37.79

Common Lisp

Three functions define the necessary conversion formulas. A fancy format string is used to print these values.

(defun to-celsius (k) 
  (- k 273.15))
(defun to-fahrenheit (k) 
  (- (* k 1.8) 459.67))
(defun to-rankine (k) 
  (* k 1.8))

(defun temperature-conversion () 
  (let ((k (read))) 
    (if (numberp k) 
      (format t "Celsius: ~d~%Fahrenheit: ~d~%Rankine: ~d~%" 
        (to-celsius k) (to-fahrenheit k) (to-rankine k)) 
      (format t "Error: Non-numeric value entered."))))
Output:
* (temperature-conversion)
21
Celsius: -252.15
Fahrenheit: -421.87003
Rankine: 37.8
NIL

D

double kelvinToCelsius(in double k) pure nothrow @safe {
    return k - 273.15;
}

double kelvinToFahrenheit(in double k) pure nothrow @safe {
    return k * 1.8 - 459.67;
}

double kelvinToRankine(in double k) pure nothrow @safe {
    return k * 1.8;
}

unittest {
    import std.math: approxEqual;
    assert(approxEqual(kelvinToCelsius(21.0), -252.15));
    assert(approxEqual(kelvinToFahrenheit(21.0), -421.87));
    assert(approxEqual(kelvinToRankine(21.0), 37.8));
}

void main(string[] args) {
    import std.stdio, std.conv, std.string;

    if (args.length == 2 && isNumeric(args[1])) {
        immutable kelvin = to!double(args[1]);
        if (kelvin >= 0) {
            writefln("K  %2.2f", kelvin);
            writefln("C  %2.2f", kelvinToCelsius(kelvin));
            writefln("F  %2.2f", kelvinToFahrenheit(kelvin));
            writefln("R  %2.2f", kelvinToRankine(kelvin));
        } else
            writefln("%2.2f K is below absolute zero", kelvin);
    }
}
Output:
K  21.00

C  -252.15

F  -421.87

R  37.80

Dart

double kelvinToCelsius(double k) {
  return k - 273.15;
}

double kelvinToFahrenheit(double k) {
  return k * 1.8 - 459.67;
}

double kelvinToRankine(double k) {
  return k * 1.8;
}

void convertKelvin(double kelvin) {
  print('K = ${kelvin.toStringAsFixed(2)}');
  print('C = ${kelvinToCelsius(kelvin).toStringAsFixed(2)}');
  print('F = ${kelvinToFahrenheit(kelvin).toStringAsFixed(2)}');
  print('R = ${kelvinToRankine(kelvin).toStringAsFixed(2)}');
  print('');
}

void main() {
  convertKelvin(0.0);
  convertKelvin(21.0);
}

Delphi

program Temperature;

{$APPTYPE CONSOLE}

uses
  SysUtils;

type
  TTemp = class
  private
    fCelsius, fFahrenheit, fRankine: double;
  public
    constructor Create(aKelvin: double);
    property AsCelsius: double read fCelsius;
    property AsFahrenheit: double read fFahrenheit;
    property AsRankine: double read fRankine;
  end;

  { TTemp }

constructor TTemp.Create(aKelvin: double);
begin
  fCelsius := aKelvin - 273.15;
  fRankine := aKelvin * 9 / 5;
  fFahrenheit := fRankine - 459.67;
end;

var
  kelvin: double;
  temp: TTemp;

begin
  write('Kelvin: ');
  readln(kelvin);
  temp := TTemp.Create(kelvin);
  writeln(Format('Celsius: %.2f', [temp.AsCelsius]));
  writeln(Format('Fahrenheit: %.2f', [temp.AsFahrenheit]));
  writeln(Format('Rankine: %.2f', [temp.AsRankine]));
  temp.Free;
  readln;
end.
Output:
Kelvin: 21.00
Celsius: -252.15
F: -421.87
R: 37.80

EasyLang

k = number input
print k & " °K"
print k - 273.15 & " °C"
print k * 1.8 - 459.67 & " °F"
print k * 1.8 & " °R"

Elena

ELENA 4.1 :

import extensions;
 
convertKelvinToFahrenheit(x)
    = x * 1.8r - 459.6r;
 
convertKelvinToRankine(x)
    = x * 1.8r;
 
convertKelvinToCelsius(x) 
    = x - 273.15r;
 
public program()
{
    console.print("Enter a Kelvin Temperature: ");
    var inputVal := console.readLine();
    real kelvinTemp := 0.0r;
    try
    {
        kelvinTemp := realConvertor.convert(inputVal)
    }
    catch(Exception e)
    {
        console.printLine("Invalid input value: ", inputVal);
 
        AbortException.raise()
    };
 
    console.printLine("Kelvin: ", kelvinTemp);
    console.printLine("Fahrenheit: ", convertKelvinToFahrenheit(kelvinTemp));
    console.printLine("Rankine: ", convertKelvinToRankine(kelvinTemp));
    console.printLine("Celsius: ", convertKelvinToCelsius(kelvinTemp));
    console.readChar()
}
Output:
Enter a Kelvin Temperature: 21
Kelvin: 21.0
Fahrenheit: -421.87
Rankine: 37.8
Celsius: -252.15

Elixir

defmodule Temperature do
  def conversion(t) do
    IO.puts "K : #{f(t)}"
    IO.puts "\nC : #{f(t - 273.15)}"
    IO.puts "\nF : #{f(t * 1.8 - 459.67)}"
    IO.puts "\nR : #{f(t * 1.8)}"
  end
  
  defp f(a) do
    Float.round(a, 2)
  end
  
  def task, do: conversion(21.0)
end

Temperature.task
Output:
K : 21.0

C : -252.15

F : -421.87

R : 37.8

Erlang

% Implemented by Arjun Sunel
-module(temp_conv).
-export([main/0]).

main() ->
    conversion(21).

conversion(T) ->
    io:format("\nK : ~p\n\n",[f(T)]),
    io:format("C : ~p \n\n",[f(T - 273.15)]),
    io:format("F : ~p\n\n",[f(T * 1.8 - 459.67)]),
    io:format("R : ~p\n\n",[f(T * 1.8)]).

f(A) ->
    (round(A*100))/100 .
Output:
K : 21.0

C : -252.15 

F : -421.87

R : 37.8

ok

Euphoria

include std/console.e

atom K
while 1 do
    K = prompt_number("Enter temperature in Kelvin >=0: ",{0,4294967296})
    printf(1,"K = %5.2f\nC = %5.2f\nF = %5.2f\nR = %5.2f\n\n",{K,K-273.15,K*1.8-459.67,K*1.8})
end while
Output:
Enter temperature in Kelvin >=0: 21
K = 21.00
C = -252.15
F = -421.87
R = 37.80

Enter temperature in Kelvin >=0:

Excel

A1 : Kelvin
B1 : Celsius
C1 : Fahrenheit
D1 : Rankine
Name A2 : K
B2 : =K-273.15
C2 : =K*1.8-459.67
D2 : =K*1.8
Input in A1
Output:
  A          B          C          D
1 Kelvin     Celsius    Fahrenheit Rankine
2         21    -252.15    -421.87       37.8

LAMBDA

Excel provides a general purpose CONVERT function, which includes coverage for common temperature scales.

We can define a reusable specialisation of it by binding the name FROMKELVIN to the following lambda expression in the Name Manager of the Excel WorkBook:

(See LAMBDA: The ultimate Excel worksheet function)

FROMKELVIN
=LAMBDA(toUnit,
    LAMBDA(n,
        LET(
            REM, "Valid units :: C, F, R, K",
            
            CONVERT(
                n, "K",
                IF("R" = toUnit, 
                    "Rank",
                    toUnit
                )
            )
        )
    )
)

The example below generates the spaced list of test values on the left from the expression ENUMFROMTHENTO(240)(250)(390), applying the following custom function:

ENUMFROMTHENTO
=LAMBDA(a,
    LAMBDA(b,
        LAMBDA(z,
            LET(
                d, b - a,

                SEQUENCE(
                    1 + FLOOR.MATH((z - a)/d),
                    1, a, d
                )
            )
        )
    )
)

The four columns on the right of the output read their target format from the label cell at the top of each column.

(The last column displays an identity conversion, added as a check).

Output:
fx =FROMKELVIN(B$1)($A2)
A B C D E
1 Kelvin C F R K
2 240 -33.15 -27.67 432 240
3 250 -23.15 -9.67 450 250
4 260 -13.15 8.33 468 260
5 270 -3.15 26.33 486 270
6 280 6.85 44.33 504 280
7 290 16.85 62.33 522 290
8 300 26.85 80.33 540 300
9 310 36.85 98.33 558 310
10 320 46.85 116.33 576 320
11 330 56.85 134.33 594 330
12 340 66.85 152.33 612 340
13 350 76.85 170.33 630 350
14 360 86.85 188.33 648 360
15 370 96.85 206.33 666 370
16 380 106.85 224.33 684 380
17 390 116.85 242.33 702 390

Ezhil

# convert from Kelvin
நிரல்பாகம் கெல்வின்_இருந்து_மாற்று( k )
 பதிப்பி "Kelvin: ",k,"Celsius: ",round(k-273.15)," Fahrenheit: ",(round(k*1.8 - 459.67))," Rankine: ",(round(k*1.8))
முடி

கெல்வின்_இருந்து_மாற்று( 0 ) #absolute zero
கெல்வின்_இருந்து_மாற்று( 273 ) #freezing pt of water
கெல்வின்_இருந்து_மாற்று( 30 + 273 ) #room temperature in Summer

F#

// Define units of measure
[<Measure>] type k
[<Measure>] type f
[<Measure>] type c
[<Measure>] type r

// Define conversion functions
let kelvinToCelsius (t : float<k>) = ((float t) - 273.15) * 1.0<c>
let kelvinToFahrenheit (t : float<k>) = (((float t) * 1.8) - 459.67) * 1.0<f>
let kelvinToRankine (t : float<k>) = ((float t) * 1.8) * 1.0<r>

// Example code
let K = 21.0<k>
printfn "%A Kelvin is %A Celsius" K (kelvinToCelsius K)
printfn "%A Kelvin is %A Fahrenheit" K (kelvinToFahrenheit K)
printfn "%A Kelvin is %A Rankine" K (kelvinToRankine K)

Factor

USING: combinators formatting kernel math ;
IN: rosetta-code.temperature

: k>c ( kelvin -- celsius )    273.15 - ;
: k>r ( kelvin -- rankine )    9/5 * ;
: k>f ( kelvin -- fahrenheit ) k>r 459.67 - ;

: convert ( kelvin -- )
    { [ ] [ k>c ] [ k>f ] [ k>r ] } cleave
    "K  %.2f\nC  %.2f\nF  %.2f\nR  %.2f\n" printf ;
    
21 convert
Output:
K  21.00
C  -252.15
F  -421.87
R  37.80

FOCAL

01.10 ASK "TEMPERATURE IN KELVIN", K
01.20 TYPE "K ", %6.02, K, !
01.30 TYPE "C ", %6.02, K - 273.15, !
01.40 TYPE "F ", %6.02, K * 1.8 - 459.67, !
01.50 TYPE "R ", %6.02, K * 1.8, !
Output:
TEMPERATURE IN KELVIN:373.15
K =  373.15
C =  100.00
F =  212.00
R =  671.67

Forth

Works with: GNU Forth

for the command line handling

: k>°C  ( F: kelvin  -- celsius )     273.15e0 f- ;
: k>°R  ( F: kelvin  -- rankine )     1.8e0 f* ;
: °R>°F ( F: rankine -- fahrenheit )  459.67e0 f- ;
: k>°F  ( F: kelvin  -- fahrenheit )  k>°R °R>°F ;
: main
   argc 1 > if  1 arg >float
      fdup      f. ." K"  cr
      fdup k>°C f. ." °C" cr
      fdup k>°F f. ." °F" cr
      fdup k>°R f. ." °R" cr
   then ;

main bye
Output:
> gforthamd64 rosetta_temp_conv.fs 21
21. K
-252.15 °C
-421.87 °F
37.8 °R

Fortran

Works with: Fortran version 90 and later
Program Temperature
  implicit none
  
  real :: kel, cel, fah, ran

  write(*,*) "Input Kelvin temperature to convert"
  read(*,*) kel

  call temp_convert(kel, cel, fah, ran)
  write(*, "((a10), f10.3)") "Kelvin", kel
  write(*, "((a10), f10.3)") "Celsius", cel
  write(*, "((a10), f10.3)") "Fahrenheit", fah
  write(*, "((a10), f10.3)") "Rankine", ran
    
contains

subroutine temp_convert(kelvin, celsius, fahrenheit, rankine)
  real, intent(in)  :: kelvin
  real, intent(out) :: celsius, fahrenheit, rankine

  celsius = kelvin - 273.15
  fahrenheit = kelvin * 1.8 - 459.67
  rankine = kelvin * 1.8

end subroutine
end program

Go

package main

import (
    "fmt"
    "os"
    "strconv"
)

func main() {
    if len(os.Args) != 2 {
        fmt.Println("Usage: k <Kelvin>")
        return
    }
    k, err := strconv.ParseFloat(os.Args[1], 64)
    if err != nil {
        fmt.Println(err)
        return
    }
    if k < 0 {
        fmt.Println("Kelvin must be >= 0.")
        return
    }
    fmt.Printf("K  %.2f\n", k)
    fmt.Printf("C  %.2f\n", k-273.15)
    fmt.Printf("F  %.2f\n", k*9/5-459.67)
    fmt.Printf("R  %.2f\n", k*9/5)
}
Output:
> k 21
K  21.00
C  -252.15
F  -421.87
R  37.80

Groovy

class Convert{
static void main(String[] args){
def c=21.0;
println("K "+c)
println("C "+k_to_c(c));
println("F "+k_to_f(k_to_c(c)));
println("R "+k_to_r(c));
}
static def k_to_c(def k=21.0){return k-273.15;}
static def k_to_f(def k=21.0){return ((k*9)/5)+32;}
static def k_to_r(def k=21.0){return k*1.8;}
}
Output:
K 21.0
C -252.15
F -421.87
R 37.80

Haskell

import System.Exit (die)
import Control.Monad (mapM_)

main = do
  putStrLn "Please enter temperature in kelvin: "
  input <- getLine
  let kelvin = read input
  if kelvin < 0.0
      then die "Temp cannot be negative"
      else mapM_ putStrLn $ convert kelvin

convert :: Double -> [String]
convert n = zipWith (++) labels nums
    where labels      = ["kelvin: ", "celcius: ", "farenheit: ", "rankine: "]
          conversions = [id, subtract 273, subtract 459.67 . (1.8 *), (*1.8)]
          nums        = (show . ($n)) <$> conversions

Or with properly managed exceptions:

{-# LANGUAGE LambdaCase #-}

import System.Exit (die)
import Control.Monad (mapM_)
import Control.Error.Safe (tryAssert, tryRead)
import Control.Monad.Trans (liftIO)
import Control.Monad.Trans.Except

main = putStrLn "Please enter temperature in kelvin: " >>
       runExceptT getTemp >>=
       \case Right x  -> mapM_ putStrLn $ convert x
             Left err -> die err

convert :: Double -> [String]
convert n = zipWith (++) labels nums
    where labels      = ["kelvin: ", "celcius: ", "farenheit: ", "rankine: "]
          conversions = [id, subtract 273, subtract 459.67 . (1.8 *), (1.8 *)]
          nums        = (show . ($ n)) <$> conversions
           
getTemp :: ExceptT String IO Double
getTemp = do 
    t <- liftIO getLine >>= tryRead "Could not read temp" 
    tryAssert "Temp cannot be negative" (t>=0)
    return t

Icon and Unicon

The following program works in both languages:

procedure main(A)
    k := A[1] | 21.00
    write("K ",k)
    write("C ",k-273.15)
    write("R ",r := k*(9.0/5.0))
    write("F ",r - 459.67)
end

Sample runs:

->tc
K 21.0
C -252.15
R 37.8
F -421.87
->tc 273.15
K 273.15
C 0.0
R 491.67
F 32.0
->

Insitux

(var K->C (+ -273.15))
(var K->R (* 1.8))
(var K->F (comp K->R (+ -459.67)))

(function kelvin-conversions K
  (let [C R F] ((juxt K->C K->R K->F) K)
       [C R F] (map @(round 2) [C R F]))
  (print K " K / " C " °C / " R " °R / " F " °F"))

(kelvin-conversions 21.0)
;prints "21 K / -252.15 °C / 37.8 °R / -421.87 °F"

J

Solution:

   NB.  Temp conversions are all linear polynomials
   K2K    =:     0    1    NB. K = (1  *k) +   0
   K2C    =:  _273    1    NB. C = (1  *k) - 273
   K2F    =:  _459.67 1.8  NB. F = (1.8*k) - 459.67
   K2R    =:     0    1.8  NB. R = (1.8*k) +   0

   NB.  Do all conversions at once (eval 
   NB.  polynomials in parallel). This is the
   NB.  numeric matrix J programs would manipulate
   NB.  directly.
   k2KCFR =:  (K2K , K2C , K2F ,: K2R) p./ ]
Example:
   NB. Format matrix for printing & tag each
   NB. temp with scale, for human legibility
   fmt    =:  [: (;:inv"1) 0 _1 |: 'KCFR' ;"0 1"_1 '0.2' 8!:0 ]
   kcfr   =:  fmt@k2KCFR
   
   kcfr 21
K   21.00
C -252.00
F -421.87
R   37.80

   kcfr 0 NB. Absolute zero
K    0.00
C -273.00
F -459.67
R    0.00

   kcfr 21 100 300  NB. List of temps works fine
K   21.00  100.00  300.00
C -252.00 -173.00   27.00
F -421.87 -279.67   80.33
R   37.80  180.00  540.00

Notes: The approach is founded on polynomials, one for each conversion (e.g. Fahrenheit = 1.8*x - 459.67 where x is measured in degrees Kelvin), and all polynomials are evaluated simultaneously using the built-in p.. Through some code decorations (specifically the / in p./ the "0 1"_1 and the 0 _1 |:), we permit our function to convert arrays of temperatures of arbitrarily high dimension (a single temp, lists of temps, tables of temps, cubes of temps, etc).

Java

public class TemperatureConversion {
    public static void main(String args[]) {
        if (args.length == 1) {
            try {
                double kelvin = Double.parseDouble(args[0]);
                if (kelvin >= 0) {
                    System.out.printf("K  %2.2f\n", kelvin);
                    System.out.printf("C  %2.2f\n", kelvinToCelsius(kelvin));
                    System.out.printf("F  %2.2f\n", kelvinToFahrenheit(kelvin));
                    System.out.printf("R  %2.2f\n", kelvinToRankine(kelvin));
                } else {
                    System.out.printf("%2.2f K is below absolute zero", kelvin);
                }
            } catch (NumberFormatException e) {
                System.out.println(e);
            }
        }
    }

    public static double kelvinToCelsius(double k) {
        return k - 273.15;
    }

    public static double kelvinToFahrenheit(double k) {
        return k * 1.8 - 459.67;
    }

    public static double kelvinToRankine(double k) {
        return k * 1.8;
    }
}
Output:
K  21.00

C  -252.15

F  -421.87

R  37.80

JavaScript

ES5

var k2c = k => k - 273.15
var k2r = k => k * 1.8
var k2f = k => k2r(k) - 459.67

Number.prototype.toMaxDecimal = function (d) {
    return +this.toFixed(d) + ''
}

function kCnv(k) {
    document.write( k,'K° = ', k2c(k).toMaxDecimal(2),'C° = ', k2r(k).toMaxDecimal(2),'R° = ', k2f(k).toMaxDecimal(2),'F°<br>' ) 
}
 
kCnv(21)
kCnv(295)
Output:
21K° = -252.15C° = 37.8R° = -421.87F°
295K° = 21.85C° = 531R° = 71.33F°

ES6

Deriving kelvinTranslations() from a more general heatBabel() function.

(() => {
    'use strict';

    let kelvinTranslations = k => ['K', 'C', 'F', 'R']
        .map(x => [x, heatBabel(k, 'K', x)]);

    // heatBabel :: Num -> ScaleName -> ScaleName -> Num
    let heatBabel = (n, strFromScale, strToScale) => {
        let ratio = 9 / 5,
            cels = 273.15,
            fahr = 459.67,
            id = x => x,
            readK = {
                k: id,
                c: x => cels + x,
                f: x => (fahr + x) * ratio,
                r: x => x / ratio
            },
            writeK = {
                k: id,
                c: x => x - cels,
                f: x => (x * ratio) - fahr,
                r: x => ratio * x
            };

        return writeK[strToScale.charAt(0).toLowerCase()](
            readK[strFromScale.charAt(0).toLowerCase()](n)
        ).toFixed(2);
    };


    // TEST
    return kelvinTranslations(21)
        .map(([s, n]) => s + ('          ' + n)
            .slice(-10))
        .join('\n');

})();
Output:
K     21.00
C   -252.15
F   -421.87
R     37.80

jq

The hard part here is defining round/1 generically.

# round(keep) takes as input any jq (i.e. JSON) number and emits a string.
# "keep" is the desired maximum number of numerals after the decimal point,
# e.g. 9.999|round(2) => 10.00
def round(keep):
  tostring
  | (index("e") | if . then . else index("E") end) as $e
  | if $e then (.[0:$e] | round(keep)) + .[$e+1:]
    else index(".") as $ix
      | if $ix == null then .
        else .[0:$ix + 1] as $head
          | .[$ix+1:$ix+keep+2] as $tail
          | if ($tail|length) <= keep then $head + $tail
            else ($tail | .[length-1:] | tonumber) as $last
              | if $last < 5 then  $head + $tail[0:$tail|length - 1]
                else (($head + $tail) | length) as $length
                  | ($head[0:-1] + $tail)
                  | (tonumber +  (if $head[0:1]=="-" then -5 else 5 end))
                  | tostring 
                  | .[0: ($ix+1+length-$length)] + "." + .[length-keep-1:-1]
                end
            end
        end
    end;

def k2c: . - 273.15;
def k2f: . * 1.8 - 459.67;
def k2r: . * 1.8;

# produce a stream
def cfr: 
  if . >= 0
  then "Kelvin: \(.)", "Celsius: \(k2c|round(2))",
       "Fahrenheit: \(k2f|round(2))", "Rankine: \(k2r|round(2))"
  else error("cfr: \(.) is an invalid temperature in degrees Kelvin")
  end;

cfr

Example

 $ jq -M -r -f Temperature_conversion.jq
  21
  Kelvin: 21
  Celsius: -252.15
  Fahrenheit: -421.87
  Rankine: 37.80
  
  -1
  jq: error: cfr: -1 is an invalid temperature in degrees Kelvin

Julia

cfr(k) = print("Kelvin: $k, ",
  "Celsius: $(round(k-273.15,2)), ",
  "Fahrenheit: $(round(k*1.8-459.67,2)), ",
  "Rankine: $(round(k*1.8,2))")
julia> cfr(21)
Kelvin: 21, Celsius: -252.15, Fahrenheit: -421.87, Rankine: 37.8

Kotlin

// version 1.1.2

class Kelvin(val degrees: Double) {
    fun toCelsius() = degrees - 273.15

    fun toFahreneit() = (degrees - 273.15) * 1.8 + 32.0

    fun toRankine() = (degrees - 273.15) * 1.8 + 32.0 + 459.67
}

fun main(args: Array<String>) {
    print("Enter the temperature in degrees Kelvin : ")
    val degrees = readLine()!!.toDouble()
    val k = Kelvin(degrees)
    val f = "% 1.2f"
    println() 
    println("K  ${f.format(k.degrees)}\n")
    println("C  ${f.format(k.toCelsius())}\n")
    println("F  ${f.format(k.toFahreneit())}\n")
    println("R  ${f.format(k.toRankine())}")
}
Output:
Enter the temperature in degrees Kelvin : 21

K   21.00

C  -252.15

F  -421.87

R   37.80

Lambdatalk

{def to-celsius {lambda {:k} {- :k 273.15}}}
-> to-celsius

{def to-farenheit {lambda {:k} {- {* :k 1.8} 459.67}}}
-> to-farenheit

{def to-rankine {lambda {:k} {* :k 1.8}}}
-> to-rankine

{def format {lambda {:n} {/ {round {* :n 100}} 100}}}
-> format

{def kelvinConversion
 {lambda {:k}
  kelvin is equivalent to:{br}
  {format {to-celsius :k}} celsius{br}
  {format {to-farenheit :k}} farenheit{br}
  {format {to-rankine :k}} rankine}}
-> kelvinConversion

{kelvinConversion 21}
-> 
kelvin is equivalent to:
 -252.15 celsius
 -421.87 farenheit
 37.8 rankine

Lasso

define tempconverter(temp, kind) => {

    local(
        _temp       = decimal(#temp),
        convertratio    = 1.8,
        k_c     = 273.15,
        r_f     = 459.67,
        k,c,r,f
    )

    match(#kind) => {
        case('k')
            #k = #_temp
            #c = -#k_c + #k
            #r = #k * #convertratio
            #f = -#r_f + #r
        case('c')
            #c = #_temp
            #k = #k_c + #c
            #r = #k * #convertratio
            #f = -#r_f + #r
        case('r')
            #r = #_temp
            #f = -#r_f + #r
            #k = #r / #convertratio
            #c = -#k_c + #k
        case('f')
            #f = #_temp
            #r = #r_f + #f
            #k = #r / #convertratio
            #c = -#k_c + #k
        case
            return 'Something wrong'
    }

    return ('K = ' + #k -> asstring(-precision = 2) +
        ' C = ' + #c -> asstring(-precision = 2) +
        ' R = ' + #r -> asstring(-precision = 2) +
        ' F = ' + #f -> asstring(-precision = 2)
        )
}

tempconverter(21, 'k')
'<br />'
tempconverter(21, 'c')
'<br />'
tempconverter(-41, 'c')
'<br />'
tempconverter(37.80, 'r')
'<br />'
tempconverter(69.80, 'f')
K = 21.00 C = -252.15 R = 37.80 F = -421.87
K = 294.15 C = 21.00 R = 529.47 F = 69.80
K = 232.15 C = -41.00 R = 417.87 F = -41.80
K = 21.00 C = -252.15 R = 37.80 F = -421.87
K = 294.15 C = 21.00 R = 529.47 F = 69.80

LIL

# Temperature conversion, in LIL
func kToc k {expr $k - 273.15}
func kTor k {expr $k / 5.0 * 9.0}
func kTof k {expr [kTor $k] - 469.67}

write "Enter kelvin temperatures or just enter to quit: "
for {set k [readline]} {![streq $k {}]} {set k [readline]} {
    print "Kelvin:     $k"
    print "Celsius:    [kToc $k]"
    print "Fahrenheit: [kTof $k]"
    print "Rankine:    [kTor $k]"
}
Output:
prompt$ lil temperatureConversion.lil 
Enter kelvin temperatures or just enter to quit: 21
Kelvin:     21
Celsius:    -252.150000
Fahrenheit: -431.870000
Rankine:    37.800000

LiveCode

function convertDegrees k
    put k/5 * 9 into r
    put k - 273.15 into c
    put r - 459.67 into f
    return k,r,c,f
end convertDegrees

Example

put convertDegrees(21.00) into tTemp
put item 1 of tTemp into temperature["Kelvin"]
put item 2 of tTemp into temperature["Rankine"]
put item 3 of tTemp into temperature["Celsius"]
put item 4 of tTemp into temperature["Fahrenheit"]
combine temperature using comma and colon
put temperature

-- Celsius:-252.15,Fahrenheit:-421.87,Kelvin:21.00,Rankine:37.8

Lua

function convert_temp(k)
    local c = k - 273.15
    local r = k * 1.8
    local f = r - 459.67
    return k, c, r, f
end

print(string.format([[
Kelvin: %.2f K
Celcius: %.2f °C
Rankine: %.2f °R
Fahrenheit: %.2f °F
]],convert_temp(21.0)))

Maple

tempConvert := proc(k)
    seq(printf("%c: %.2f\n", StringTools[UpperCase](substring(i, 1)), convert(k, temperature, kelvin, i)), i in [kelvin, Celsius, Fahrenheit, Rankine]);
    return NULL;
end proc:

tempConvert(21);
Output:
K: 21.00
C: -252.15
F: -421.87
R: 37.80

Mathematica/Wolfram Language

tempConvert[t_] := # -> Thread@UnitConvert[#,{"DegreesFahrenheit", "DegreesCelsius", "DegreesRankine"}]&@Quantity[N@t, "Kelvins"]
tempConvert[21]
Output:
21.K -> {-421.87°F,-252.15°C,37.8°R}

min

Works with: min version 0.19.3
(
  ((float) (273.15 -) (9 5 / * 459.67 -) (9 5 / *)) cleave
  () 'cons 4 times "K  $1\nC  $2\nF  $3\nR  $4" swap % puts!
) :convert

21 convert
Output:
K  21.0
C  -252.15
F  -421.87
R  37.8

MiniScript

fromKelvin = function(temp)
    print temp + " degrees in Kelvin is:"
    Celsius = temp - 273.15
    print Celsius + " degrees Celsius"
    Fahrenheit = round(Celsius  * 9/5 + 32,2)
    print Fahrenheit + " degrees Fahrenheit"
    Rankine = Fahrenheit + 459.67
    print Rankine + " degrees Rankine"
end function

temp = input("Enter a temperature in Kelvin: ")
fromKelvin temp.val
Output:
enter a temperature in Kelvin: 273.15
273.15 degrees in Kelvin is :-
0 degrees Celsius
32 degrees Fahrenheit
491.67 degrees Rankine

Enter a temperature in Kelvin: 300
300 degrees in Kelvin is:
26.85 degrees Celsius
80.33 degrees Fahrenheit
540 degrees Rankine

MiniZinc

float: kelvin;

var float: celsius;
var float: fahrenheit;
var float: rankine;

constraint celsius == kelvin - 273.15;
constraint fahrenheit == celsius * 1.8 + 32;
constraint rankine == fahrenheit + 459.67;
solve satisfy;

output ["K \(kelvin)\n", "C \(celsius)\n", "F \(fahrenheit)\n", "R \(rankine)\n"];
Output:

Compiling temperature.mzn, additional arguments kelvin=1000; Running temperature.mzn K 1000.0 C 726.850000000001 F 1340.33 R 1800.0 ---------- Finished in 62msec

МК-61/52

П7   0   ,   8   *   П8  ИП7 9   *   5
/   3   2   +   П9  ИП7 2   7   3   ,
1   5   +   П4  С/П П8  1   ,   8   /
БП  00  П9  3   2   -   5   *   9   /
БП  00  П4  2   7   3   ,   1   5   -
БП  00

Instruction:

tºC = РX В/О С/П;

tºRa = РX БП 25 С/П;

tºF = РX БП 32 С/П;

tK = РX БП 42 С/П;

Result:

РX = Р4 = tK;

Р7 = tºC;

Р8 = tºRa;

Р9 = tºF.

ML

mLite

Temperature in Kelvin given on command line.

fun KtoC n = n - 273.15;
fun KtoF n = n * 1.8 - 459.67;
fun KtoR n = n * 1.8;
val K = argv 0;

if K = false then
    println "mlite -f temcon.m <temp>"
else
    let 
        val K = ston K
    in 
        print "Kelvin:     "; println K;
        print "Celcius:    "; println ` KtoC K;
        print "Fahrenheit: "; println ` KtoF K;
        print "Rankine:    "; println ` KtoR K
    end

Nanoquery

Translation of: Python
% while true
  ...   print "K ? "   
  ...   k = float(input())
  ... 
  ...   println format("%g Kelvin = %g Celsius = %g Fahrenheit = %g Rankine degrees.", k, k-273.15, k*1.8-459.67, k*1.8)
  ... end
K ? 21
21.0000 Kelvin = -252.150 Celsius = -421.870 Fahrenheit = 37.8000 Rankine degrees.
K ? 222.2
222.200 Kelvin = -50.9500 Celsius = -59.7100 Fahrenheit = 399.960 Rankine degrees.
K ?

NetRexx

/* NetRexx */
options replace format comments java crossref symbols

numeric digits 20

runSample(arg)
return

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/*
  +  Kelvin               Celsius        Fahrenheit      Rankine             Delisle        Newton            Réaumur        Rømer
  K  T                    T-273.15       T*9/5-459.67    T*9/5               (373.15-T)*3/2 (T-273.15)*33/100 (T-273.15)*4/5 (T-273.15)*21/40+7.5
  C  T+273.15             T              T*9/5+32        (T+273.15)*9/5      (100-T)*3/2    T*33/100          T*4/5          T*21/40+7.5
  F  (T+459.67)*5/9       (T-32)*5/9     T               T+459.67            (212-T)*5/6    (T-32)*11/60      (T-32)*4/9     (T-32)*7/24+7.5
  R  T*5/9                (T-491.67)*5/9 T-459.67        T                   (671.67-T)*5/6 (T-491.67)*11/60  (T-491.67)*4/9 (T-491.67)*7/24+7.5
  De 373.15-T*2/3         100-T*2/3      212-T*6/5       671.67-T*6/5        T              33-T*11/50        80-T*8/15      60-T*7/20
  N  T*100/33+273.15      T*100/33       T*60/11+32      T*60/11+491.67      (33-T)*50/11   T                 T*80/33        T*35/22+7.5
  Ré T*5/4+273.15         T*5/4          T*9/4+32        T*9/4+491.67        (80-T)*15/8    T*33/80           T              T*21/32+7.5
  Rø (T-7.5)*40/21+273.15 (T-7.5)*40/21  (T-7.5)*24/7+32 (T-7.5)*24/7+491.67 (60-T)*20/7    (T-7.5)*22/35     (T-7.5)*32/21  T
 */
method temperatureConversion(scaleFrom, scaleTo, T) public static

  parse 'KELVIN CELSIUS FAHRENHEIT RANKINE DELISLE NEWTON REAUMUR ROEMER' -
         KELVIN CELSIUS FAHRENHEIT RANKINE DELISLE NEWTON REAUMUR ROEMER .
  scaleFrom = scaleFrom.upper()
  scaleTo   = scaleTo.upper()
  select label sF case scaleFrom
    when KELVIN then do
      select case scaleTo
        when KELVIN     then val = T
        when CELSIUS    then val = T - 273.15
        when FAHRENHEIT then val = T * 9 / 5 - 459.67
        when RANKINE    then val = T * 9 / 5
        when DELISLE    then val = (373.15 - T) * 3 / 2
        when NEWTON     then val = (T - 273.15) * 33 / 100
        when REAUMUR    then val = (T - 273.15) * 4 / 5
        when ROEMER     then val = (T - 273.15) * 21 / 40 + 7.5
        otherwise       signal IllegalArgumentException(scaleFrom',' scaleTo',' T)
        end
      end
    when CELSIUS then do
      select case scaleTo
        when KELVIN     then val = T + 273.15
        when CELSIUS    then val = T
        when FAHRENHEIT then val = T * 9 / 5 + 32
        when RANKINE    then val = (T + 273.15) * 9 / 5
        when DELISLE    then val = (100 - T) * 3 / 2
        when NEWTON     then val = T * 33 / 100
        when REAUMUR    then val = T * 4 / 5
        when ROEMER     then val = T * 21 / 40 + 7.5
        otherwise       signal IllegalArgumentException(scaleFrom',' scaleTo',' T)
        end
      end
    when FAHRENHEIT then do
      select case scaleTo
        when KELVIN     then val = (T + 459.67) * 5 / 9
        when CELSIUS    then val = (T - 32) * 5 / 9
        when FAHRENHEIT then val = T
        when RANKINE    then val = T + 459.67
        when DELISLE    then val = (212 - T) * 5 / 6
        when NEWTON     then val = (T - 32) * 11 / 60
        when REAUMUR    then val = (T - 32) * 4 / 9
        when ROEMER     then val = (T - 32) * 7 / 24 + 7.5
        otherwise       signal IllegalArgumentException(scaleFrom',' scaleTo',' T)
        end
      end
    when RANKINE then do
      select case scaleTo
        when KELVIN     then val = T * 5 / 9
        when CELSIUS    then val = (T - 491.67) * 5 / 9
        when FAHRENHEIT then val = T - 459.67
        when RANKINE    then val = T
        when DELISLE    then val = (671.67 - T) * 5 / 6
        when NEWTON     then val = (T - 491.67) * 11 / 60
        when REAUMUR    then val = (T - 491.67) * 4 / 9
        when ROEMER     then val = (T - 491.67) * 7 / 24 + 7.5
        otherwise       signal IllegalArgumentException(scaleFrom',' scaleTo',' T)
        end
      end
    when DELISLE then do
      select case scaleTo
        when KELVIN     then val = 373.15 - T * 2 / 3
        when CELSIUS    then val = 100 - T * 2 / 3
        when FAHRENHEIT then val = 212 - T * 6 / 5
        when RANKINE    then val = 671.67 - T * 6 / 5
        when DELISLE    then val = T
        when NEWTON     then val = 33 - T * 11 / 50
        when REAUMUR    then val = 80 - T * 8 / 15
        when ROEMER     then val = 60 - T * 7 / 20
        otherwise       signal IllegalArgumentException(scaleFrom',' scaleTo',' T)
        end
      end
    when NEWTON then do
      select case scaleTo
        when KELVIN     then val = T * 100 / 33 + 273.15
        when CELSIUS    then val = T * 100 / 33
        when FAHRENHEIT then val = T * 60 / 11 + 32
        when RANKINE    then val = T * 60 / 11 + 491.67
        when DELISLE    then val = (33 - T) * 50 / 11
        when NEWTON     then val = T
        when REAUMUR    then val = T * 80 / 33
        when ROEMER     then val = T * 35 / 22 + 7.5
        otherwise       signal IllegalArgumentException(scaleFrom',' scaleTo',' T)
        end
      end
    when REAUMUR then do
      select case scaleTo
        when KELVIN     then val = T * 5 / 4 + 273.15
        when CELSIUS    then val = T * 5 / 4
        when FAHRENHEIT then val = T * 9 / 4 + 32
        when RANKINE    then val = T * 9 / 4 + 491.67
        when DELISLE    then val = (80 - T) * 15 / 8
        when NEWTON     then val = T * 33 / 80
        when REAUMUR    then val = T
        when ROEMER     then val = T * 21 / 32 + 7.5
        otherwise       signal IllegalArgumentException(scaleFrom',' scaleTo',' T)
        end
      end
    when ROEMER then do
      select case scaleTo
        when KELVIN     then val = (T - 7.5) * 40 / 21 + 273.15
        when CELSIUS    then val = (T - 7.5) * 40 / 21
        when FAHRENHEIT then val = (T - 7.5) * 24 / 7 + 32
        when RANKINE    then val = (T - 7.5) * 24 / 7 + 491.67
        when DELISLE    then val = (60 - T) * 20 / 7
        when NEWTON     then val = (T - 7.5) * 22 / 35
        when REAUMUR    then val = (T - 7.5) * 32 / 21
        when ROEMER     then val = T
        otherwise       signal IllegalArgumentException(scaleFrom',' scaleTo',' T)
        end
      end
    otherwise
      signal IllegalArgumentException(scaleFrom',' scaleTo',' T)
    end sF

  return val

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method runSample(arg) public static

  tlist = [ -
  /* C....... F....... K....... R.......*/ -
    ' 5500.00  9932.00  5773.15 10391.67', -
    '  300.00   572.00   573.15  1031.67', -
    '  200.00   392.00   473.15   851.67', -
    '  100.00   212.00   373.15   671.67', -
    '   37.00    98.60   310.15   558.27', -
    '    0.00    32.00   273.15   491.67', -
    ' -100.00  -148.00   173.15   311.67', -
    ' -200.00  -328.00    73.15   131.67', -
    ' -252.15  -421.87    21.00    37.80', -
    ' -273.15  -459.67     0.00     0.00'  -
    ]

  parse 'CELSIUS FAHRENHEIT KELVIN RANKINE' CELSIUS FAHRENHEIT KELVIN RANKINE .
  loop temp over tlist
    parse temp ttC ttF ttK ttR .
    say '   C....... F....... K....... R.......'
    say 'C ' -
        temperatureConversion(CELSIUS,    CELSIUS,    ttC).format(5, 2) -
        temperatureConversion(CELSIUS,    FAHRENHEIT, ttC).format(5, 2) -
        temperatureConversion(CELSIUS,    KELVIN,     ttC).format(5, 2) -
        temperatureConversion(CELSIUS,    RANKINE,    ttC).format(5, 2)
  
    say 'F ' -
        temperatureConversion(FAHRENHEIT, CELSIUS,    ttF).format(5, 2) -
        temperatureConversion(FAHRENHEIT, FAHRENHEIT, ttF).format(5, 2) -
        temperatureConversion(FAHRENHEIT, KELVIN,     ttF).format(5, 2) -
        temperatureConversion(FAHRENHEIT, RANKINE,    ttF).format(5, 2)
  
    say 'K ' -
        temperatureConversion(KELVIN,     CELSIUS,    ttK).format(5, 2) -
        temperatureConversion(KELVIN,     FAHRENHEIT, ttK).format(5, 2) -
        temperatureConversion(KELVIN,     KELVIN,     ttK).format(5, 2) -
        temperatureConversion(KELVIN,     RANKINE,    ttK).format(5, 2)
  
    say 'R ' -
        temperatureConversion(RANKINE,    CELSIUS,    ttR).format(5, 2) -
        temperatureConversion(RANKINE,    FAHRENHEIT, ttR).format(5, 2) -
        temperatureConversion(RANKINE,    KELVIN,     ttR).format(5, 2) -
        temperatureConversion(RANKINE,    RANKINE,    ttR).format(5, 2)
    say
    end temp

  return
Output:
   C....... F....... K....... R.......
C   5500.00  9932.00  5773.15 10391.67
F   5500.00  9932.00  5773.15 10391.67
K   5500.00  9932.00  5773.15 10391.67
R   5500.00  9932.00  5773.15 10391.67

   C....... F....... K....... R.......
C    300.00   572.00   573.15  1031.67
F    300.00   572.00   573.15  1031.67
K    300.00   572.00   573.15  1031.67
R    300.00   572.00   573.15  1031.67

   C....... F....... K....... R.......
C    200.00   392.00   473.15   851.67
F    200.00   392.00   473.15   851.67
K    200.00   392.00   473.15   851.67
R    200.00   392.00   473.15   851.67

   C....... F....... K....... R.......
C    100.00   212.00   373.15   671.67
F    100.00   212.00   373.15   671.67
K    100.00   212.00   373.15   671.67
R    100.00   212.00   373.15   671.67

   C....... F....... K....... R.......
C     37.00    98.60   310.15   558.27
F     37.00    98.60   310.15   558.27
K     37.00    98.60   310.15   558.27
R     37.00    98.60   310.15   558.27

   C....... F....... K....... R.......
C      0.00    32.00   273.15   491.67
F      0.00    32.00   273.15   491.67
K      0.00    32.00   273.15   491.67
R      0.00    32.00   273.15   491.67

   C....... F....... K....... R.......
C   -100.00  -148.00   173.15   311.67
F   -100.00  -148.00   173.15   311.67
K   -100.00  -148.00   173.15   311.67
R   -100.00  -148.00   173.15   311.67

   C....... F....... K....... R.......
C   -200.00  -328.00    73.15   131.67
F   -200.00  -328.00    73.15   131.67
K   -200.00  -328.00    73.15   131.67
R   -200.00  -328.00    73.15   131.67

   C....... F....... K....... R.......
C   -252.15  -421.87    21.00    37.80
F   -252.15  -421.87    21.00    37.80
K   -252.15  -421.87    21.00    37.80
R   -252.15  -421.87    21.00    37.80

   C....... F....... K....... R.......
C   -273.15  -459.67     0.00     0.00
F   -273.15  -459.67     0.00     0.00
K   -273.15  -459.67     0.00     0.00
R   -273.15  -459.67     0.00     0.00

Never

func KtoC(k : float) -> float { k - 273.15 }
func KtoF(k : float) -> float { k * 1.8 - 459.67 }
func KtoR(k : float) -> float { k * 1.8 }

func convertK(k : float) -> int {
    prints("K " + k + "\n");
    prints("C " + KtoC(k) + "\n");
    prints("F " + KtoF(k) + "\n");
    prints("R " + KtoR(k) + "\n");
    0
}

func main(k : float) -> int {
    convertK(k);
    0
}
Output:
K 21.00
C -252.15
F -421.87
R 37.80

NewLISP

(define (to-celsius k)
    (- k 273.15)
)

(define (to-fahrenheit k)
    (- (* k 1.8) 459.67)
)

(define (to-rankine k)
    (* k 1.8)
)

(define (kelvinConversion k)
    (if (number? k)
        (println k " kelvin is equivalent to:\n" 
            (to-celsius k) " celsius\n" 
            (to-fahrenheit k) " fahrenheit\n" 
            (to-rankine k) " rankine")
        (println "Please enter a number only, with no º or letter. ")
    )
)
Output:
21 kelvin is equivalent to:
-252 celsius
-438 fahrenheit
21 rankine

Nim

Library: strfmt
import rdstdin, strutils, strfmt

while true:
  let k = parseFloat readLineFromStdin "K ? "
  echo "{:g} Kelvin = {:g} Celsius = {:g} Fahrenheit = {:g} Rankine degrees".fmt(
    k, k - 273.15, k * 1.8 - 459.67, k * 1.8)

Sample usage:

K ? 21.0
21 Kelvin = -252.15 Celsius = -421.87 Fahrenheit = 37.8 Rankine degrees
K ? 222.2
222.2 Kelvin = -50.95 Celsius = -59.71 Fahrenheit = 399.96 Rankine degrees

Objeck

class Temperature {
  function : Main(args : String[]) ~ Nil {
    k := System.IO.Console->ReadString()->ToFloat();
    c := KelvinToCelsius(k);
    f := KelvinToFahrenheit(k);
    r := KelvinToRankine(k);

    "K: {$k}"->PrintLine();
    "C: {$c}"->PrintLine();
    "F: {$f}"->PrintLine();
    "R: {$r}"->PrintLine();
  }

  function : KelvinToCelsius(k : Float) ~ Float {
    return k - 273.15;
  }
 
  function : KelvinToFahrenheit(k : Float) ~ Float {
    return k * 1.8 - 459.67;
  }
 
  function : KelvinToRankine(k : Float) ~ Float {
    return k * 1.8;
  }
}
K: 21.0
C: -252.150
F: -421.870
R: 37.800

Objective-C

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[])
{
    @autoreleasepool {
        if(argc > 1)
        {
            NSString *arg1 = [NSString stringWithCString:argv[1] encoding:NSUTF8StringEncoding]; 
            // encoding shouldn't matter in this case
            double kelvin = [arg1 doubleValue];
            
            NSLog(@"K %.2f",kelvin);
            NSLog(@"C %.2f\n", kelvin - 273.15);
            NSLog(@"F %.2f\n", (kelvin * 1.8) - 459.67);
            NSLog(@"R %.2f", kelvin * 1.8);
        }
    }
    return 0;
}

OCaml

let print_temp s t =
  print_string s;
  print_endline (string_of_float t);;

let kelvin_to_celsius k =
  k -. 273.15;;

let kelvin_to_fahrenheit k =
  (kelvin_to_celsius k)*. 9./.5. +. 32.00;;

let kelvin_to_rankine k =
  (kelvin_to_celsius k)*. 9./.5. +. 491.67;;


print_endline "Enter a temperature in Kelvin please:";
let k = read_float () in
print_temp "K " k;
print_temp "C " (kelvin_to_celsius k);
print_temp "F " (kelvin_to_fahrenheit k);
print_temp "R " (kelvin_to_rankine k);;

Sample session:

Enter a temperature in Kelvin please:
184
K 184.
C -89.15
F -128.47
R 331.2

Oforth

: kelvinToCelsius  273.15 - ;
: kelvinToFahrenheit   1.8 * 459.67 - ;
: kelvinToRankine  1.8 * ;

: testTemp(n)
   n kelvinToCelsius println
   n kelvinToFahrenheit println
   n kelvinToRankine println ;
Output:
>21 testTemp
-252.15
-421.87
37.8

ooRexx

Translation of: REXX
/* REXX convert temperatures from/to 58 temperature scakes                       */
Parse Source src
Parse Var src . how .

If how='FUNCTION' Then
  If arg(2)='' Then
    tlist=arg(1) 'TO' 'K'
  Else
    tlist=arg(1) 'TO' arg(2)
Else Do
  Parse Arg tList                          /* get the list of pairs                */
  If arg(1)='?' Then Call help
  tList= space(tList)                      /* elide any and all superfluous blanks.*/
  End
Do While tList>''                          /* process the list                     */
  Parse Var tList pair ',' tList           /* pairs are separated by commas        */
  Parse       Var pair from_to '(' desc    /* get spec and description (If any)    */
  Parse upper Var from_to fromt ' TO' toscal . /* get temperature and target scale */
  If toscal=='' Then Do                    /* no target scale: show all targets    */
    If how='FUNCTION' Then Do
      all=0
      toscal='K'
      End
    Else Do
      all=1
      toscale='all'
      End
    End
  Else Do
    all=0
    toscale=scalename(toscal)
    End

  Parse Var fromt fromtemp fromscal
  If fromscal='' Then
    fromscale='K'                       /*assume kelvin as per task requirement*/
  Else
    fromscale=scalename(fromscal)

  If fromt='' Then Call serr 'No source temperature specified'
  If \datatype(fromtemp,'N') Then Call serr 'Source temperature ('fromtemp') not numeric'
  If left(fromscale,1)='*' Then Call serr 'Invalid source scale' fromscale
  If left(toscale,1)='*' Then Call serr 'Invalid target scale' toscale

  F=convert2Fahrenheit(fromtemp fromscale) /*convert a temperature --? Fahrenheit.*/

  If F<-459.67 Then Call serr 'Source temperature below absolute zero'

  If how<>'FUNCTION' Then Do            /* write a header line                    */
    If desc<>'' Then desc='('desc
    Say pair                /*show original value & scale (for sep)*/
    If toscale<>'' Then
      Say fromtemp fromscale 'TO' toscale
    Else
      Say fromtemp fromscale 'TO' all
    End

  Call convert2specific

  End   /* while tlist>'' */
Exit                                     /* stick a fork in it, we're all done.  */

scaleName:
 Parse Arg sn                            /* abbreviations --> temp. short name.  */
 snU=translate(sn)                       /* uppercase version of temperature unit*/
 snU=translate(snU,'-eE',"_éÉ")          /* translate some accented characters.  */

 If left(snU,7)=='DEGREES' Then          /* is this a redundant "degrees"  ?     */
   snU=substr(snU,8)
 If left(snU,6)=='DEGREE' Then           /* "  "    " "         "degree"  ?      */
   snU=substr(snU,7)
 snU=strip(snU)                          /* elide all leading & trailing blanks  */
 _= length(snU)                          /* obtain the length of the  snU  value */

 If right(snU,1)=='S' & _>1 Then
   snU=left(snU,_-1)                     /* remove any trailing plural(s)        */

 Select                                  /* get scalename from abbrevuation      */
   When abbrev('ALL'                     , snU, 3)    Then sn= "ALL"
   When abbrev('ABSOLUTE'                , snU, 1)    Then sn= "ABSOLUTE"
   When abbrev('AMONTON'                 , snU)       Then sn= "AMONTON"
   When abbrev('BARNDORF'                , snU,2)  |,
        abbrev('BARNSDORF'               , snU,2)     Then sn= "BARNSDORF"
   When abbrev('BEAUMIUR'                , snU,3)  |,
        abbrev('BEAUMUIR'                , snU,3)     Then sn= "BEAUMUIR"
   When abbrev('BENERT'                  , snU,3)  |,
        abbrev('BENART'                  , snU,3)     Then sn= "BENART"
   When abbrev('BRISSEN'                 , snU,3)  |,
        abbrev('BRISSON'                 , snU,3)     Then sn= "BRISSEN"
   When abbrev('BURGEN'                  , snU,3)  |,
        abbrev('BURGAN'                  , snU,3)  |,
        abbrev('BERGAN'                  , snU,3)  |,
        abbrev('BERGEN'                  , snU,3)     Then sn= "BERGEN"
   When abbrev('CENTIGRADE'              , snU)    |,
        abbrev('CENTRIGRADE'             , snU)    |,       /* 50% misspelled.*/
        abbrev('CETIGRADE'               , snU)    |,       /* 50% misspelled.*/
        abbrev('CENTINGRADE'             , snU)    |,
        abbrev('CENTESIMAL'              , snU)    |,
        abbrev('CELCIU'                  , snU)    |,       /* 82% misspelled.*/
        abbrev('CELCIOU'                 , snU)    |,       /*  4% misspelled.*/
        abbrev('CELCUI'                  , snU)    |,       /*  4% misspelled.*/
        abbrev('CELSUI'                  , snU)    |,       /*  2% misspelled.*/
        abbrev('CELCEU'                  , snU)    |,       /*  2% misspelled.*/
        abbrev('CELCU'                   , snU)    |,       /*  2% misspelled.*/
        abbrev('CELISU'                  , snU)    |,       /*  1% misspelled.*/
        abbrev('CELSU'                   , snU)    |,       /*  1% misspelled.*/
        abbrev('HECTOGRADE'              , snU)    |,
        abbrev('CELSIU'                  , snU)       Then sn= "CELSIUS"
   When abbrev('CIMANTO'                 , snU,2)  |,
        abbrev('CIMENTO'                 , snU,2)     Then sn= "CIMENTO"
   When abbrev('CRUQUIOU'                , snU,2)  |,
        abbrev('CRUQUIO'                 , snU,2)  |,
        abbrev('CRUQUIU'                 , snU,2)     Then sn= "CRUQUIU"
   When abbrev('DALANCE'                 , snU,4)  |,
        abbrev('DALENCE'                 , snU,4)     Then sn= "DALENCE"
   When abbrev('DANELLE'                 , snU,3)  |,
        abbrev('DANEAL'                  , snU,3)  |,
        abbrev('DANIAL'                  , snU,3)  |,
        abbrev('DANIELE'                 , snU,3)  |,
        abbrev('DANNEL'                  , snU,3)  |,
        abbrev('DANYAL'                  , snU,3)  |,
        abbrev('DANYEL'                  , snU,3)  |,
        abbrev('DANIELL'                 , snU,3)     Then sn= "DANIELL"
   When abbrev('DALTON'                  , snU,3)     Then sn= "DALTON"
   When abbrev('DELAHIRE'                , snU,7)  |,
        abbrev('LAHIRE'                  , snU,4)  |,
        abbrev('HIRE'                    , snU,2)  |,
        abbrev('DE-LA-HIRE'              , snU,7)     Then sn= "DE LA HIRE"
   When abbrev('DELAVILLE'               , snU,7)  |,
        abbrev('LAVILLE'                 , snU,3)  |,
        abbrev('VILLE'                   , snU,1)  |,
        abbrev('VILLA'                   , snU,1)  |,
        abbrev('DE-LA-VILLE'             , snU,7)     Then sn= "DE LA VILLE"
   When abbrev('DELISLE'                 , snU,3)     Then sn= "DELISLE"
   When abbrev('DELISLE-OLD'             , snU,8)  |,
        abbrev('OLDDELISLE'              , snU,6)  |,
        abbrev('DELISLEOLD'              , snU,8)     Then sn= "DELISLE OLD"
   When abbrev('DELUC'                   , snU,4)  |,
        abbrev('LUC'                     , snU,2)  |,
        abbrev('DE-LUC'                  , snU,5)     Then sn= "DE LUC"
   When abbrev('DELYON'                  , snU,4)  |,
        abbrev('LYON'                    , snU,2)  |,
        abbrev('DE-LYON'                 , snU,5)     Then sn= "DE LYON"
   When abbrev('DEREVILLA'               , snU,3)  |,
        abbrev('DEREVILA'                , snU,3)  |,
        abbrev('REVILLA'                 , snU,3)  |,
        abbrev('DE-REVILLA'              , snU,4)  |,
        abbrev('DE-REVILLA'              , snU,5)     Then sn= "DE REVILLAS"
   When abbrev('DEVILLENEUVE'            , snU,3)  |,
        abbrev('DE-VILLENEUVE'           , snU,4)     Then sn= "DE VILLENEUVE"
   When abbrev('DURHAM'                  , snU,3)  |,
        abbrev('DERHAM'                  , snU,4)     Then sn= "DERHAM"
   When abbrev('OLDDURHAM'               , snU,5)  |,
        abbrev('OLDDERHAM'               , snU,6)  |,
        abbrev('DERHAM-OLD'              , snU,4)  |,
        abbrev('DERHAMOLD'               , snU,4)     Then sn= "DERHAM OLD"
   When abbrev('DE-SUEDE'                , snU,4)  |,
        abbrev('DESUEDE'                 , snU,4)     Then sn= "DE SUEDE"
   When abbrev('DU-CREST'                , snU,2)  |,
        abbrev('DUCREST'                 , snU,2)     Then sn= "DU CREST"
   When abbrev('EDENBURGH'               , snU,2)  |,
        abbrev('EDINBURGH'               , snU,2)     Then sn= "EDINBURGH"
   When abbrev('EVOLT'                   , snU,2)  |,
        abbrev('ELECTRONVOLT'            , snU,2)     Then sn= "ELECTRON VOLTS"
   When abbrev('FARENHEIT'               , snU)    |,       /* 39% misspelled.*/
        abbrev('FARENHEIGHT'             , snU)    |,       /* 15% misspelled.*/
        abbrev('FARENHITE'               , snU)    |,       /*  6% misspelled.*/
        abbrev('FARENHIET'               , snU)    |,       /*  3% misspelled.*/
        abbrev('FARHENHEIT'              , snU)    |,       /*  3% misspelled.*/
        abbrev('FARINHEIGHT'             , snU)    |,       /*  2% misspelled.*/
        abbrev('FARENHIGHT'              , snU)    |,       /*  2% misspelled.*/
        abbrev('FAHRENHIET'              , snU)    |,       /*  2% misspelled.*/
        abbrev('FERENHEIGHT'             , snU)    |,       /*  2% misspelled.*/
        abbrev('FEHRENHEIT'              , snU)    |,       /*  2% misspelled.*/
        abbrev('FERENHEIT'               , snU)    |,       /*  2% misspelled.*/
        abbrev('FERINHEIGHT'             , snU)    |,       /*  1% misspelled.*/
        abbrev('FARIENHEIT'              , snU)    |,       /*  1% misspelled.*/
        abbrev('FARINHEIT'               , snU)    |,       /*  1% misspelled.*/
        abbrev('FARANHITE'               , snU)    |,       /*  1% misspelled.*/
        abbrev('FAHRENHEIT'              , snU)       Then sn= "FAHRENHEIT"
   When abbrev('OLDFAHRENHEIT'           , snU,4)  |,
        abbrev('FAHRENHEIT-OLD'          , snU,13) |,
        abbrev('FAHRENHEITOLD'           , snU,13)    Then sn= "FARHENHEIT OLD"
   When abbrev('FLORENTINE-LARGE'        , snU,12) |,
        abbrev('LARGE-FLORENTINE'        , snU,7)  |,
        abbrev('LARGEFLORENTINE'         , snU,6)  |,
        abbrev('FLORENTINELARGE'         , snU,12)    Then sn= "FLORENTINE LARGE"
   When abbrev('FLORENTINE-MAGNUM'       , snU,2)  |,
        abbrev('MAGNUM-FLORENTINE'       , snU,3)  |,
        abbrev('MAGNUMFLORENTINE'        , snU,3)  |,
        abbrev('FLORENTINEMAGNUM'        , snU,2)     Then sn= "FLORENTINE MAGNUM"
   When abbrev('FLORENTINE-SMALL'        , snU,13) |,
        abbrev('SMALL-FLORENTINE'        , snU,7)  |,
        abbrev('SMALLFLORENTINE'         , snU,6)  |,
        abbrev('FLORENTINESMALL'         , snU,13)    Then sn= "FLORENTINE SMALL"
   When abbrev('FOULER'                  , snU,2)  |,
        abbrev('FOWLOR'                  , snU,2)  |,
        abbrev('FOWLER'                  , snU,2)     Then sn= "FOWLER"
   When abbrev('FRICK'                   , snU,2)     Then sn= "FRICK"
   When abbrev('GAS-MARK'                , snU,2)  |,
        abbrev('GASMARK'                 , snU,2)     Then sn= "GAS MARK"
   When abbrev('GOUBERT'                 , snU,2)     Then sn= "GOUBERT"
   When abbrev('HAIL'                    , snU,3)  |,
        abbrev('HALE'                    , snU,3)     Then sn= "HALES"
   When abbrev('HANOW'                   , snU,3)     Then sn= "HANOW"
   When abbrev('HUCKSBEE'                , snU,3)  |,
        abbrev('HAWKSBEE'                , snU,3)  |,
        abbrev('HAUKSBEE'                , snU,3)     Then sn= "HAUKSBEE"
   When abbrev('JACOBSHOLBORN'           , snU,2)  |,
        abbrev('JACOBS-HOLBORN'          , snU,2)     Then sn= "JACOBS-HOLBORN"
   When abbrev('KALVIN'                  , snU)    |,       /* 27% misspelled.*/
        abbrev('KERLIN'                  , snU)    |,       /* 18% misspelled.*/
        abbrev('KEVEN'                   , snU)    |,       /*  9% misspelled.*/
        abbrev('KELVIN'                  , snU)       Then sn= "KELVIN"
   When abbrev('LAYDEN'                  , snU)    |,
        abbrev('LEIDEN'                  , snU)       Then sn= "LEIDEN"
   When abbrev('NEUTON'                  , snU)    |,       /*100% misspelled.*/
        abbrev('NEWTON'                  , snU)       Then sn= "NEWTON"
   When abbrev('ORTEL'                   , snU)    |,
        abbrev('OERTEL'                  , snU)       Then sn= "OERTEL"
   When abbrev('PLACK'                   , snU)    |,       /*100% misspelled.*/
        abbrev('PLANC'                   , snU)    |,       /*     misspelled.*/
        abbrev('PLANK'                   , snU)    |,       /*     misspelled.*/
        abbrev('PLANCK'                  , snU)       Then sn= "PLANCK"
   When abbrev('RANKINE'                 , snU, 1)    Then sn= "RANKINE"
   When abbrev('REAUMUR'                 , snU, 2)    Then sn= "REAUMUR"
   When abbrev('RICKTER'                 , snU, 3) |,
        abbrev('RICHTER'                 , snU, 3)    Then sn= "RICHTER"
   When abbrev('RINALDINI'               , snU, 3)    Then sn= "RINALDINI"
   When abbrev('ROEMER'                  , snU, 3) |,
        abbrev('ROMER'                   , snU, 3)    Then sn= "ROMER"
   When abbrev('ROSANTHAL'               , snU, 3) |,
        abbrev('ROSENTHAL'               , snU, 3)    Then sn= "ROSENTHAL"
   When abbrev('RSOL'                    , snU, 2) |,
        abbrev('RSL'                     , snU, 2) |,
        abbrev('ROYALSOCIETYOFLONDON'    , snU, 3) |,
        abbrev('ROYAL-SOCIETY-OF-LONDON' , snU, 3)    Then sn= "ROYAL SOCIETY"
   When abbrev('SAGREDO'                 , snU, 3)    Then sn= "SAGREDO"
   When abbrev('ST.-PATRICE'             , snU, 3) |,
        abbrev('ST.PATRICE'              , snU, 3) |,
        abbrev('SAINTPATRICE'            , snU, 3) |,
        abbrev('SAINT-PATRICE'           , snU, 3)    Then sn= "SAINT-PATRICE"
   When abbrev('STUFFE'                  , snU, 3) |,
        abbrev('STUFE'                   , snU, 3)    Then sn= "STUFE"
   When abbrev('SULTZER'                 , snU, 2) |,
        abbrev('SULZER'                  , snU, 2)    Then sn= "SULZER"
   When abbrev('WEDGEWOOD'               , snU)    |,
        abbrev('WEDGWOOD'                , snU)       Then sn= "WEDGWOOD"
   Otherwise
     sn='***' sn '***'
   End   /*Select*/
Return sn

convert2Fahrenheit: /*convert N --? ºF temperatures. */
/* [?]  fifty-eight temperature scales.*/
Parse Arg n sn
Select
  When sn=='ABSOLUTE'           Then F= n *   9/5      - 459.67
  When sn=='AMONTON'            Then F= n * 8.37209    - 399.163
  When sn=='BARNSDORF'          Then F= n * 6.85714    +   6.85714
  When sn=='BEAUMUIR'           Then F= n * 2.22951    +  32
  When sn=='BENART'             Then F= n * 1.43391    +  31.2831
  When sn=='BERGEN'             Then F=(n + 23.8667)   *  15/14
  When sn=='BRISSEN'            Then F= n *  32/15     +  32
  When sn=='CELSIUS'            Then F= n *   9/5      +  32  /* C -> Celsius.*/
  When sn=='CIMENTO'            Then F= n * 2.70677    -   4.54135
  When sn=='CRUQUIUS'           Then F= n * 0.409266   - 405.992
  When sn=='DALENCE'            Then F= n * 2.7        +  59
  When sn=='DALTON'             Then F=rxCalcexp(rxCalclog(373.15/273.15)*n/100)*9*273.15/5-459.67
--When sn=='DALTON'             Then F=273.15*rxCalcexp(273.15/273.15,n/100)*1.8-459.67
  When sn=='DANIELL'            Then F= n * 7.27194    +  55.9994
  When sn=='DE LA HIRE'         Then F=(n - 3)         /   0.549057
  When sn=='DE LA VILLE'        Then F=(n + 6.48011)   /   0.985568
  When sn=='DELISLE'            Then F=212             -   n * 6/5
  When sn=='DELISLE OLD'        Then F=212             -   n * 1.58590197
  When sn=='DE LUC'             Then F=(n + 14)        *  16/7
  When sn=='DE LYON'            Then F=(n + 17.5)      *  64/35
  When sn=='DE REVILLAS'        Then F=212             -   n * 97/80
  When sn=='DERHAM'             Then F= n / 0.38444386 - 188.578
  When sn=='DERHAM OLD'         Then F= n * 3          +   4.5
  When sn=='DE SUEDE'           Then F=(n + 17.6666)   * 150/83
  When sn=='DE VILLENEUVE'      Then F=(n + 23.7037)   /   0.740741
  When sn=='DU CREST'           Then F=(n + 37.9202)   /   0.650656
  When sn=='EDINBURGH'          Then F= n * 4.6546     -   6.40048
  When sn=='ELECTRON VOLTS'     Then F= n * 20888.1    - 459.67
  When sn=='FAHRENHEIT'         Then F= n
  When sn=='FAHRENHEIT OLD'     Then F= n * 20/11      -  89.2727
  When sn=='FLORENTINE LARGE'   Then F=(n +  7.42857)  /   0.857143
  When sn=='FLORENTINE MAGNUM'  Then F=(n + 73.9736 )  /   1.50659
  When sn=='FLORENTINE SMALL'   Then F=(n -  1.38571)  /   0.378571
  When sn=='FOWLER'             Then F= n * 0.640321   +  53.7709
  When sn=='FRICK'              Then F= n * 200/251    +  58.5339
  When sn=='GASMARK'            Then F= n * 25         + 250
  When sn=='GOUBERT'            Then F= n * 2          +  32
  When sn=='HALES'              Then F= n * 1.2        +  32
  When sn=='HANOW'              Then F= n * 1.06668    -  10.6672
  When sn=='HAUKSBEE'           Then F= n *  18/25     +  88.16
  When sn=='JACOBS-HOLBORN'     Then F= n *  18/71     -  53.4366
  When sn=='K'                  Then F= n *   9/5      - 459.67
  When sn=='KELVIN'             Then F= n *   9/5      - 459.67
  When sn=='LEIDEN'             Then F= n * 1.8        - 423.4
  When sn=='NEWTON'             Then F= n *  60/11     +  32
  When sn=='OERTEL'             Then F= n + n          -  32
  When sn=='PLANCK'             Then F= n * 1.416833e32*   9/5  -  459.67
  When sn=='RANKINE'            Then F= n              - 459.67  /* R -> Rankine.*/
  When sn=='REAUMUR'            Then F= n *   9/4      +  32
  When sn=='RICHTER'            Then F= n * 160/73     -   7.45205
  When sn=='RINALDINI'          Then F= n * 15         +  32
  When sn=='ROMER'              Then F=(n - 7.5) * 27/4+  32
  When sn=='ROSENTHAL'          Then F= n *  45/86     - 453.581
  When sn=='ROYAL SOCIETY'      Then F=(n -122.82)     * -50/69
  When sn=='SAGREDO'            Then F= n * 0.3798     -   5.98
  When sn=='SAINT-PATRICE'      Then F= n * 2.62123    + 115.879
  When sn=='STUFE'              Then F= n * 45         + 257
  When sn=='SULZER'             Then F= n * 1.14595    +  33.2334
  When sn=='THERMOSTAT'         Then F= n * 54         +  32
  When sn=='WEDGWOOD'           Then F= n * 44.7429295 + 516.2
  Otherwise Call serr  'invalid temperature scale: '
  End   /*Select*/
Return F

convert2specific: /*convert ºF --? xxx temperatures.*/

K=(F+459.67)*5/9                       /*compute temperature in kelvin scale. */
a=(1e||(-digits()%2)-digits()%20)      /*minimum number for Dalton temperature*/
eV=(F+459.67)/20888.1                  /*compute the number of electron volts.*/

If ?('ABSOLUTE') Then Call line fn(k) "Absolute"
If ?('AMONTON') Then Call line  fn((F+399.163) / 8.37209 ) "Amonton"
If ?('BARNSDORF') Then Call line fn( ( F - 6.85715) / 6.85715 ) "Barnsdorf"
If ?('BEAUMUIR') Then Call line fn( ( F - 32 ) / 2.22951 ) "Beaumuir"
If ?('BENART') Then Call line fn( ( F - 31.2831 ) / 1.43391 ) "Benart"
If ?('BERGEN') Then Call line fn( ( F * 14/15 ) - 23.8667 ) "Bergen"
If ?('BRISSON') Then Call line fn( ( F - 32 ) * 15/32 ) "Brisson"
If ?('CELSIUS') Then Call line fn( ( F - 32 ) * 5/9 ) "Celsius"
If ?('CIMENTO') Then Call line fn( ( F + 4.54135) / 2.70677 ) "Cimento"
If ?('CRUQUIUS') Then Call line fn( ( F + 405.992 ) / 0.409266 ) "Cruquius"
If ?('DALENCE') Then Call line fn( ( F - 59 ) / 2.7 ) "Dalence"
If ?('DALTON') Then Do
 If K>a Then Call line fn(100*rxCalclog(k/273.15)/rxCalclog(373.15/273.15) ) "Dalton"
 Else Call line right("-infinity        ", 60) "Dalton"
 End
If ?('DANIELL') Then Call line fn( ( F - 55.9994 ) / 7.27194 ) "Daniell"
If ?('DE LA HIRE') Then Call line fn( F * 0.549057 + 3 ) "De la Hire"
If ?('DE LA VILLE') Then Call line fn( F * 0.985568 - 6.48011 ) "De la Ville"
If ?('DELISLE') Then Call line fn( ( 212 - F ) * 5/6 ) "Delisle"
If ?('DELISLE OLD') Then Call line fn( ( 212 - F ) / 1.58590197 ) "Delisle OLD"
If ?('DE LUC') Then Call line fn( F * 7/16 - 14 ) "De Luc"
If ?('DE LYON') Then Call line fn( F * 35/64 - 17.5 ) "De Lyon"
If ?('DE REVILLAS') Then Call line fn( ( 212 - F ) * 80/97 ) "De Revillas"
If ?('DERHAM') Then Call line fn( F * 0.38444386 + 72.4978 ) "Derham"
If ?('DERHAM OLD') Then Call line fn( ( F - 4.5 ) / 3 ) "Derham OLD"
If ?('DE VILLENEUVE') Then Call line fn( F * 0.740741 - 23.7037 ) "De Villeneuve"
If ?('DE SUEDE') Then Call line fn( F * 83/150 - 17.6666 ) "De Suede"
If ?('DU CREST') Then Call line fn( F * 0.650656 - 37.9202 ) "Du Crest"
If ?('EDINBURGH') Then Call line fn( ( F + 6.40048) / 4.6546 ) "Edinburgh"
If ?('ELECTRON VOLTS') Then Call line fn( eV ) "electron volt"s(eV)
If ?('FAHRENHEIT') Then Call line fn( F ) "Fahrenheit"
If ?('FAHRENHEIT OLD') Then Call line fn( F * 20/11 - 89.2727 ) "Fahrenheit OLD"
If ?('FLORENTINE LARGE') Then Call line fn( F * 0.857143 - 7.42857 ) "Florentine large"
If ?('FLORENTINE MAGNUM') Then Call line fn( F * 1.50659 - 73.9736 ) "Florentine Magnum"
If ?('FLORENTINE SMALL') Then Call line fn( F * 0.378571 + 1.38571 ) "Florentine small"
If ?('FOWLER') Then Call line fn( ( F - 53.7709 ) / 0.640321 ) "Fowler"
If ?('FRICK') Then Call line fn( ( F - 58.5338 ) * 251/200 ) "Frick"
If ?('GAS MARK') Then Call line fn( ( F - 250 ) * 0.04 ) "gas mark"
If ?('GOUBERT') Then Call line fn( ( F + 32 ) * 0.5 ) "Goubert"
If ?('HALES') Then Call line fn( ( F - 32 ) / 1.2 ) "Hales"
If ?('HANOW') Then Call line fn( ( F + 10.6672 ) / 1.06668 ) "Hanow"
If ?('HAUKSBEE') Then Call line fn( ( F - 88.16 ) * 25/18 ) "Hauksbee"
If ?('JACOBS-HOLBORN') Then Call line fn( ( F + 53.4366 ) * 71/18 ) "Jacobs-Holborn"
If ?('KELVIN') Then Call line fn( k ) 'KELVIN'
If ?('LEIDEN') Then Call line fn( F / 1.8 + 235.222 ) "Leiden"
If ?('NEWTON') Then Call line fn( ( F - 32 ) * 11/60 ) "Newton"
If ?('OERTEL') Then Call line fn( ( F + 32 ) * 0.5 ) "Oertel"
If ?('PLANCK') Then Call line fn( ( F + 459.67 ) * 5/9 / 1.416833e32 ) "Planck"
If ?('RANKINE') Then Call line fn( F + 459.67 ) "Rankine"
If ?('REAUMUR') Then Call line fn( ( F - 32 ) * 4/9 ) "Reaumur"
If ?('RICHTER') Then Call line fn( ( F + 7.45205) * 73/160 ) "Richter"
If ?('RINALDINI') Then Call line fn( ( F - 32 ) / 15 ) "Rinaldini"
If ?('ROMER') Then Call line fn( ( F - 32 ) * 4/27 + 7.5 ) "Romer"
If ?('ROSENTHAL') Then Call line fn( ( F + 453.581 ) * 86/45 ) "Rosenthal"
If ?('ROYAL SOCIETY') Then Call line fn( F * -69/50 + 122.82 ) "Royal Society of London"
If ?('SAGREDO') Then Call line fn( ( F + 5.98 ) / 0.3798 ) "Segredo"
If ?('SAINT-PATRICE') Then Call line fn( ( F - 115.879 ) / 2.62123 ) "Saint-Patrice"
If ?('STUFE') Then Call line fn( ( F - 257 ) / 45 ) "Stufe"
If ?('SULZER') Then Call line fn( ( F - 33.2334 ) / 1.14595 ) "Sulzer"
If ?('THERMOSTAT') Then Call line fn( ( F - 32 ) / 54 ) "Thermostat"
If ?('WEDGWOOD') Then Call line fn( ( F - 516.2 ) / 44.7429295 ) "Wedgwood"
Return

line:
  If how='FUNCTION' & all=0 Then
    Exit space(arg(1))
  Else
    Say arg(1)
  Return

?:
  Return (arg(1)=toscale | all)

fn: Procedure Expose how result
 showDig=8                                /* only show 8 decimal digs.              */
 number=commas(format(arg(1),,showDig)/1) /* format# 8 digits past . and add commas */
 p=pos('.',number)                        /* find position of the decimal point.    */
                                          /* [?]  align integers with FP numbers.   */
 If p==0 Then                             /* no  decimal point                     .*/
   number=number||left('',5+showDig+1)
 Else                                     /* ddd.ddd                                */
   number=number||left('',5+showDig-length(number)+p)
 Return right(number,max(25,length(number)))/* return the re-formatted argument (#).*/

commas: Procedure
Parse Arg u
a=pos('.',u'.')
e=1
If left(u,1)='-' Then e=2
Do j=a-4 To e by -3
  u=insert(',',u,j)
  End
Return u

s:
 If arg(1)==1 Then Return arg(3)
 Return word(arg(2)'s',1) /*pluralizer.*/

serr:
 If how='FUNCTION' Then
   Exit arg(1)
 Else
   Say arg(1)
 Exit 13

help:
  Say 'use as command:'
  Say 'rexx tcw fromtemp [fromscale] [TO toscale | all],...'
  Say 'or as function'
  Say 'tcw(fromtemp [fromscale] [TO toscale])'
  Exit
::Requires rxmath library
Output:
K:\_B\TC>rexx tcwoo 0 C to fa
0 C to fa
0 CELSIUS TO FAHRENHEIT
         32               Fahrenheit
K:\_B\TC>rexx tcwoo 0 f
0 f
0 FAHRENHEIT TO all
        255.372222        Absolute
         47.67782         Amonton
         -1               Barnsdorf
        -14.3529296       Beaumuir
        -21.8166412       Benart
        -23.8667          Bergen
        -15               Brisson
        -17.7777778       Celsius
          1.67777462      Cimento
        992.000313        Cruquius
        -21.8518519       Dalence
        -21.5729747       Dalton
         -7.70075111      Daniell
          3               De la Hire
         -6.48011         De la Ville
        176.666667        Delisle
        133.677872        Delisle OLD
        -14               De Luc
        -17.5             De Lyon
        174.845361        De Revillas
         72.4978          Derham
         -1.5             Derham OLD
        -23.7037          De Villeneuve
        -17.6666          De Suede
        -37.9202          Du Crest
          1.37508701      Edinburgh
          0.02200631      electron volts
          0               Fahrenheit
        -89.2727          Fahrenheit OLD
         -7.42857         Florentine large
        -73.9736          Florentine Magnum
          1.38571         Florentine small
        -83.9749126       Fowler
        -73.459919        Frick
        -10               gas mark
         16               Goubert
        -26.6666667       Hales
         10.000375        Hanow
       -122.444444        Hauksbee
        210.7777          Jacobs-Holborn
        255.372222        KELVIN
        235.222           Leiden
         -5.86666667      Newton
         16               Oertel
          1.80241582E-30  Planck
        459.67            Rankine
        -14.2222222       Reaumur
          3.39999781      Richter
         -2.13333333      Rinaldini
          2.75925926      Romer
        866.843689        Rosenthal
        122.82            Royal Society of London
         15.745129        Segredo
        -44.2078719       Saint-Patrice
         -5.71111111      Stufe
        -29.0007417       Sulzer
         -0.59259259      Thermostat
        -11.5370184       Wedgwood

PARI/GP

f(x)=[x,x-273.15,1.8*x-459.67,1.8*x]

Pascal

program TemperatureConvert;

type
    TemperatureType = (C, F, K, R);

var
    kelvin: real;

    function ConvertTemperature(temperature: real; fromType, toType: TemperatureType): real;

    var
        initial, result: real;

    begin
        (* We are going to first convert whatever we're given into Celsius.
           Then we'll convert that into whatever we're asked to convert into.
           Maybe not the most efficient way to do this, but easy to understand
           and should make it easier to add any additional temperature units. *)
        if fromType <> toType then
            begin
                case fromType of (* first convert the temperature into Celsius *)
                    C:
                        initial := temperature;
                    F:
                        initial := (temperature - 32) / 1.8;
                    K:
                        initial := temperature - 273.15;
                    R:
                        initial := (temperature - 491.67) / 1.8;
                end;
                case toType of (* now convert from Celsius into whatever degree type was asked for *)
                    C:
                        result := initial;
                    F:
                        result := (initial * 1.8) + 32;
                    K:
                        result := initial + 273.15;
                    R:
                        result := (initial * 1.8) + 491.67;
                end;
            end
        else (* no point doing all that math if we're asked to convert from and to the same type *)
            result := temperature;
        ConvertTemperature := result;
    end;

begin
    write('Temperature to convert (in kelvins): ');
    readln(kelvin);
    writeln(kelvin : 3 : 2, ' in kelvins is ');
    writeln('    ', ConvertTemperature(kelvin, K, C) : 3 : 2, ' in degrees Celsius.');
    writeln('    ', ConvertTemperature(kelvin, K, F) : 3 : 2, ' in degrees Fahrenheit.');
    writeln('    ', ConvertTemperature(kelvin, K, R) : 3 : 2, ' in degrees Rankine.');
end.
Output:
Temperature to convert (in kelvins): 373.15
373.15 in kelvins is 
    100.00 in degrees Celsius.
    212.00 in degrees Fahrenheit.
    671.67 in degrees Rankine.

Perl

my %scale = (
    Celcius    => { factor => 1  , offset => -273.15 },
    Rankine    => { factor => 1.8, offset =>    0    },
    Fahrenheit => { factor => 1.8, offset => -459.67 },
);

print "Enter a temperature in Kelvin: ";
chomp(my $kelvin = <STDIN>);
die "No such temperature!\n" unless $kelvin > 0;

foreach (sort keys %scale) {
    printf "%12s:%8.2f\n", $_, $kelvin * $scale{$_}{factor} + $scale{$_}{offset};
}
Output:
Enter a temperature in Kelvin: 21
     Celcius: -252.15
  Fahrenheit: -421.87
     Rankine:   37.80

Phix

Modified copy of Euphoria

atom K = prompt_number("Enter temperature in Kelvin >=0: ",{0,1e307})
printf(1,"    Kelvin: %5.2f\n   Celsius: %5.2f\nFahrenheit: %5.2f\n   Rankine: %5.2f\n\n",
                      {K,                 K-273.15,          K*1.8-459.67,      K*1.8})
Output:
Enter temperature in Kelvin >=0: 300
    Kelvin: 300.00
   Celsius: 26.85
Fahrenheit: 80.33
   Rankine: 540.00

PHP

while (true) {
    echo "\nEnter a value in kelvin (q to quit): ";
    if ($kelvin = trim(fgets(STDIN))) {
        if ($kelvin == 'q') {
            echo 'quitting';
            break;
        }
        if (is_numeric($kelvin)) {
            $kelvin = floatVal($kelvin);
            if ($kelvin >= 0) {
                printf(" K  %2.2f\n", $kelvin);
                printf(" C  %2.2f\n", $kelvin - 273.15);
                printf(" F  %2.2f\n", $kelvin * 1.8 - 459.67);
                printf(" R  %2.2f\n", $kelvin * 1.8);
            } else printf(" %2.2f K is below absolute zero\n", $kelvin);
        }
    }
}
Output:
Enter a value in kelvin (q to quit): 21
 K  21.00
 C  -252.15
 F  -421.87
 R  37.80

Enter a value in kelvin (q to quit): q
quitting

PicoLisp

(scl 2)

(de convertKelvin (Kelvin)
   (for X
      (quote
         (K . prog)
         (C (K) (- K 273.15))
         (F (K) (- (*/ K 1.8 1.0) 459.67))
         (R (K) (*/ K 1.8 1.0)) )
      (tab (-3 8)
         (car X)
         (format ((cdr X) Kelvin) *Scl) ) ) )

Test:

(convertKelvin 21.0)
Output:
K     21.00
C   -252.15
F   -421.87
R     37.80

PL/I

*process source attributes xref;
 /* PL/I **************************************************************
 * 15.08.2013 Walter Pachl translated from NetRexx
 * temperatures below 0K are considered invalid
 *********************************************************************/
 temperature: Proc Options(main);
 Dcl sysin record Input;
 On Endfile(sysin) Goto eoj;
 On Record(sysin);
 Dcl 1 dat,
      2 t Pic'SSSS9V.99',
      2 *    char( 1),
      2 from char(10),
      2 *    char( 1),
      2 to   char(10);
 Do Forever;
   Read File(sysin) Into(dat);
   If tc(t,from,'KELVIN')<0 Then
     Put Edit('Input (',t,from,') invalid. Below absolute zero')
             (Skip,a,f(8,2),x(1),a,a);
   Else
     Put edit(t,from,' -> ',tc(t,from,to),to)
             (skip,f(8,2),x(1),a(10),a,f(8,2),x(1),a(10));
   End;
 eoj: Return;

 tc: Procedure(T,scaleFrom,scaleTo) Returns(Dec Fixed(8,2));
 Dcl t Pic'SSSS9V.99';
 Dcl (val) Dec Fixed(8,2);
 Dcl (scaleFrom,scaleTo) Char(10);
  select(scaleFrom);
    when('KELVIN ') do;
      select(scaleTo);
        when('KELVIN    ') val = T;
        when('CELSIUS   ') val = T - 273.15;
        when('FAHRENHEIT') val = T * 9 / 5 - 459.67;
        when('RANKINE   ') val = T * 9 / 5;
        when('DELISLE   ') val = (373.15 - T) * 3 / 2;
        when('NEWTON    ') val = (T - 273.15) * 33 / 100;
        when('REAUMUR   ') val = (T - 273.15) * 4 / 5;
        when('ROEMER    ') val = (T - 273.15) * 21 / 40 + 7.5;
        otherwise Do;
          Put Edit('scaleTo=',scaleTo)(Skip,a,a);
          Call err(1);
          End;
        end;
      end;
    when('CELSIUS') do;
      select(scaleTo);
        when('KELVIN    ') val = T + 273.15;
        when('CELSIUS   ') val = T;
        when('FAHRENHEIT') val = T * 9 / 5 + 32;
        when('RANKINE   ') val = (T + 273.15) * 9 / 5;
        when('DELISLE   ') val = (100 - T) * 3 / 2;
        when('NEWTON    ') val = T * 33 / 100;
        when('REAUMUR   ') val = T * 4 / 5;
        when('ROEMER    ') val = T * 21 / 40 + 7.5;
        otherwise Call err(2);
        end;
      end;
    when('FAHRENHEIT') do;
      select(scaleTo);
        when('KELVIN    ') val = (T + 459.67) * 5 / 9;
        when('CELSIUS   ') val = (T - 32) * 5 / 9;
        when('FAHRENHEIT') val = T;
        when('RANKINE   ') val = T + 459.67;
        when('DELISLE   ') val = (212 - T) * 5 / 6;
        when('NEWTON    ') val = (T - 32) * 11 / 60;
        when('REAUMUR   ') val = (T - 32) * 4 / 9;
        when('ROEMER    ') val = (T - 32) * 7 / 24 + 7.5;
        otherwise Call err(3);
        end;
      end;
    when('RANKINE') do;
      select(scaleTo);
        when('KELVIN    ') val = T * 5 / 9;
        when('CELSIUS   ') val = (T - 491.67) * 5 / 9;
        when('FAHRENHEIT') val = T - 459.67;
        when('RANKINE   ') val = T;
        when('DELISLE   ') val = (671.67 - T) * 5 / 6;
        when('NEWTON    ') val = (T - 491.67) * 11 / 60;
        when('REAUMUR   ') val = (T - 491.67) * 4 / 9;
        when('ROEMER    ') val = (T - 491.67) * 7 / 24 + 7.5;
        otherwise Call err(4);
        end;
      end;
    when('DELISLE') do;
      select(scaleTo);
        when('KELVIN    ') val = 373.15 - T * 2 / 3;
        when('CELSIUS   ') val = 100 - T * 2 / 3;
        when('FAHRENHEIT') val = 212 - T * 6 / 5;
        when('RANKINE   ') val = 671.67 - T * 6 / 5;
        when('DELISLE   ') val = T;
        when('NEWTON    ') val = 33 - T * 11 / 50;
        when('REAUMUR   ') val = 80 - T * 8 / 15;
        when('ROEMER    ') val = 60 - T * 7 / 20;
        otherwise Call err(5);
        end;
      end;
    when('NEWTON') do;
      select(scaleTo);
        when('KELVIN    ') val = T * 100 / 33 + 273.15;
        when('CELSIUS   ') val = T * 100 / 33;
        when('FAHRENHEIT') val = T * 60 / 11 + 32;
        when('RANKINE   ') val = T * 60 / 11 + 491.67;
        when('DELISLE   ') val = (33 - T) * 50 / 11;
        when('NEWTON    ') val = T;
        when('REAUMUR   ') val = T * 80 / 33;
        when('ROEMER    ') val = T * 35 / 22 + 7.5;
        otherwise Call err(6);
        end;
      end;
    when('REAUMUR') do;
      select(scaleTo);
        when('KELVIN    ') val = T * 5 / 4 + 273.15;
        when('CELSIUS   ') val = T * 5 / 4;
        when('FAHRENHEIT') val = T * 9 / 4 + 32;
        when('RANKINE   ') val = T * 9 / 4 + 491.67;
        when('DELISLE   ') val = (80 - T) * 15 / 8;
        when('NEWTON    ') val = T * 33 / 80;
        when('REAUMUR   ') val = T;
        when('ROEMER    ') val = T * 21 / 32 + 7.5;
        otherwise Call err(7);
        end;
      end;
    when('ROEMER') do;
      select(scaleTo);
        when('KELVIN    ') val = (T - 7.5) * 40 / 21 + 273.15;
        when('CELSIUS   ') val = (T - 7.5) * 40 / 21;
        when('FAHRENHEIT') val = (T - 7.5) * 24 / 7 + 32;
        when('RANKINE   ') val = (T - 7.5) * 24 / 7 + 491.67;
        when('DELISLE   ') val = (60 - T) * 20 / 7;
        when('NEWTON    ') val = (T - 7.5) * 22 / 35;
        when('REAUMUR   ') val = (T - 7.5) * 32 / 21;
        when('ROEMER    ') val = T;
        otherwise Call err(8);
        end;
      end;
    otherwise Call err(9);
    end;
  return(val);
  err: Proc(e);
  Dcl e Dec fixed(1);
  Put Edit('error ',e,' invalid input')(Skip,a,f(1),a);
  val=0;
  End;
  End;
 End;
Output:
   21.00 KELVIN     ->  -252.15 CELSIUS
   21.00 KELVIN     ->  -421.87 FAHRENHEIT
   21.00 KELVIN     ->    37.80 RANKINE
Input (  600.00 DELISLE   ) invalid. Below absolute zero
Input (   -1.00 KELVIN    ) invalid. Below absolute zero
Input ( -300.00 CELSIUS   ) invalid. Below absolute zero
  212.00 FAHRENHEIT ->   100.00 CELSIUS
    0.00 FAHRENHEIT ->   -17.77 CELSIUS
    0.00 CELSIUS    ->    32.00 FAHRENHEIT
   37.00 CELSIUS    ->    98.60 FAHRENHEIT

Plain English

To run:
Start up.
Put 21 into a kelvin temperature.
Show the kelvin temperature in various temperature scales.
Wait for the escape key.
Shut down.

A temperature is a fraction.
A kelvin temperature is a temperature.
A celsius temperature is a temperature.
A rankine temperature is a temperature.
A fahrenheit temperature is a temperature.

To convert a kelvin temperature to a celsius temperature:
Put the kelvin temperature minus 273-15/100 into the celsius temperature.

To convert a kelvin temperature to a rankine temperature:
Put the kelvin temperature times 9/5 into the rankine temperature.

To convert a kelvin temperature to a fahrenheit temperature:
Convert the kelvin temperature to a rankine temperature.
Put the rankine temperature minus 459-67/100 into the fahrenheit temperature.

To show a temperature given a temperature scale string:
Write the temperature scale then " = " then the temperature then " degrees" on the console.

To show a kelvin temperature in various temperature scales:
Convert the kelvin temperature to a celsius temperature.
Convert the kelvin temperature to a fahrenheit temperature.
Convert the kelvin temperature to a rankine temperature.
Show the kelvin temperature given "K".
Show the celsius temperature given "C".
Show the fahrenheit temperature given "F".
Show the rankine temperature given "R".
Output:
K = 21 degrees
C = -252-3/20 degrees
F = -421-87/100 degrees
R = 37-4/5 degrees

PowerShell

Translation of: Tcl
function temp($k){
    try{
        $c = $k - 273.15
        $r = $k / 5 * 9
        $f = $r - 459.67
    } catch {
        Write-host "Input error."
        return
    }

    Write-host ""
    Write-host "    TEMP (Kelvin)    : " $k
    Write-host "    TEMP (Celsius)   : " $c
    Write-host "    TEMP (Fahrenheit): " $f
    Write-host "    TEMP (Rankine)   : " $r
    Write-host ""

}

$input=Read-host "Enter a temperature in Kelvin"
temp $input
Output:
PS> ./TEMPS
Enter a temperature in Kelvin: 100

        TEMP (Kelvin)    :  100
        TEMP (Celsius)   :  -173.15
        TEMP (Fahrenheit):  -279.67
        TEMP (Rankine)   :  180

PS>

PowerShell Alternate Version

A more "PowerShelly" way to do it.

function Convert-Kelvin
{
    [CmdletBinding()]
    [OutputType([PSCustomObject])]
    Param
    (
        [Parameter(Mandatory=$true,
                   ValueFromPipeline=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=0)]
        [double]
        $InputObject
    )

    Process
    {
        foreach ($kelvin in $InputObject)
        {
            [PSCustomObject]@{
                Kelvin     = $kelvin
                Celsius    = $kelvin - 273.15
                Fahrenheit = $kelvin * 1.8 - 459.67
                Rankine    = $kelvin * 1.8
            }
        }
    }
}
21, 100 | Convert-Kelvin
Output:
Kelvin Celsius Fahrenheit Rankine
------ ------- ---------- -------
    21 -252.15    -421.87    37.8
   100 -173.15    -279.67     180

Prolog

Works with: GNU Prolog
Works with: SWI Prolog
convKelvin(Temp) :-
    Kelvin is Temp,
    Celsius is Temp - 273.15,
    Fahrenheit is (Temp - 273.15) * 1.8 + 32.0,
    Rankine is (Temp - 273.15) * 1.8 + 32.0 + 459.67,
    format('~f degrees Kelvin~n', [Kelvin]),
    format('~f degrees Celsius~n', [Celsius]),
    format('~f degrees Fahrenheit~n', [Fahrenheit]),
    format('~f degrees Rankine~n', [Rankine]).

test :-
    convKelvin(0.0),
    nl,
    convKelvin(21.0).

Pure Data

temperature.pd

#N canvas 200 200 640 600 10;
#X floatatom 130 54 8 0 0 2 Kelvin chgk -;
#X obj 130 453 rnd2;
#X floatatom 130 493 8 0 0 1 K - -;
#X floatatom 251 54 8 0 0 2 Celsius chgc -;
#X obj 251 453 rnd2;
#X floatatom 251 493 8 0 0 1 °C - -;
#X floatatom 374 54 8 0 0 2 Fahrenheit chgf -;
#X obj 374 453 rnd2;
#X floatatom 374 493 8 0 0 1 °F - -;
#X floatatom 498 54 8 0 0 2 Rankine chgr -;
#X obj 498 453 rnd2;
#X floatatom 498 493 8 0 0 1 °Ra - -;
#X obj 65 133 - 273.15;
#X obj 65 244 * 1.8;
#X obj 65 267 + 32;
#X obj 65 363 + 459.67;
#X obj 186 133 * 1.8;
#X obj 186 156 + 32;
#X obj 186 268 + 459.67;
#X obj 186 310 / 1.8;
#X obj 309 133 + 459.67;
#X obj 309 215 / 1.8;
#X obj 309 291 - 273.15;
#X obj 433 133 / 1.8;
#X obj 433 223 - 273.15;
#X obj 433 294 * 1.8;
#X obj 433 317 + 32;
#X text 20 53 Input:;
#X text 20 492 Output:;
#X connect 0 0 1 0;
#X connect 0 0 12 0;
#X connect 1 0 2 0;
#X connect 3 0 4 0;
#X connect 3 0 16 0;
#X connect 4 0 5 0;
#X connect 6 0 7 0;
#X connect 6 0 20 0;
#X connect 7 0 8 0;
#X connect 9 0 10 0;
#X connect 9 0 23 0;
#X connect 10 0 11 0;
#X connect 12 0 13 0;
#X connect 12 0 4 0;
#X connect 13 0 14 0;
#X connect 14 0 15 0;
#X connect 14 0 7 0;
#X connect 15 0 10 0;
#X connect 16 0 17 0;
#X connect 17 0 18 0;
#X connect 17 0 7 0;
#X connect 18 0 19 0;
#X connect 18 0 10 0;
#X connect 19 0 1 0;
#X connect 20 0 21 0;
#X connect 20 0 10 0;
#X connect 21 0 22 0;
#X connect 21 0 1 0;
#X connect 22 0 4 0;
#X connect 23 0 24 0;
#X connect 23 0 1 0;
#X connect 24 0 25 0;
#X connect 24 0 4 0;
#X connect 25 0 26 0;
#X connect 26 0 7 0;

Plugin to round the results to at most 2 digits:

rnd.pd

#N canvas 880 200 450 300 10;
#X obj 77 34 inlet;
#X obj 77 113 * 100;
#X obj 77 135 + 0.5;
#X obj 132 135 < 0;
#X obj 77 172 -;
#X obj 77 194 int;
#X obj 77 216 / 100;
#X obj 77 238 outlet;
#X connect 0 0 1 0;
#X connect 0 0 3 0;
#X connect 1 0 2 0;
#X connect 2 0 4 0;
#X connect 3 0 4 1;
#X connect 4 0 5 0;
#X connect 5 0 6 0;
#X connect 6 0 7 0;

Python

>>> while True:
    k = float(input('K ? '))
    print("%g Kelvin = %g Celsius = %g Fahrenheit = %g Rankine degrees."
          % (k, k - 273.15, k * 1.8 - 459.67, k * 1.8))

    
K ? 21.0
21 Kelvin = -252.15 Celsius = -421.87 Fahrenheit = 37.8 Rankine degrees.
K ? 222.2
222.2 Kelvin = -50.95 Celsius = -59.71 Fahrenheit = 399.96 Rankine degrees.
K ?

Python: Universal conversion

This converts from any one of the units to all the others

>>> toK = {'C': (lambda c: c + 273.15),
           'F': (lambda f: (f + 459.67) / 1.8),
           'R': (lambda r: r / 1.8),
           'K': (lambda k: k) }
>>> while True:
    magnitude, unit = input('<value> <K/R/F/C> ? ').split()
    k = toK[unit](float(magnitude))
    print("%g Kelvin = %g Celsius = %g Fahrenheit = %g Rankine degrees."
          % (k, k - 273.15, k * 1.8 - 459.67, k * 1.8))

    
<value> <K/R/F/C> ? 222.2 K
222.2 Kelvin = -50.95 Celsius = -59.71 Fahrenheit = 399.96 Rankine degrees.
<value> <K/R/F/C> ? -50.95 C
222.2 Kelvin = -50.95 Celsius = -59.71 Fahrenheit = 399.96 Rankine degrees.
<value> <K/R/F/C> ? -59.71 F
222.2 Kelvin = -50.95 Celsius = -59.71 Fahrenheit = 399.96 Rankine degrees.
<value> <K/R/F/C> ? 399.96 R
222.2 Kelvin = -50.95 Celsius = -59.71 Fahrenheit = 399.96 Rankine degrees.
<value> <K/R/F/C> ?

Quackery

All the conversions.

Using the Quackery big number rational arithmetic library bigrat.qky.

  [ $ "bigrat.qky" loadfile ] now! 
 
  [ 5 9 v* ]                        is r->k ( n/d --> n/d ) 
  [ 1/v r->k 1/v ]                  is k->r ( n/d --> n/d )
 
  [ 45967 100 v- ]                  is r->f ( n/d --> n/d )
  [ -v r->f -v ]                    is f->r ( n/d --> n/d )
 
  [ 5463 20 v- ]                    is k->c ( n/d --> n/d )
  [ -v k->c -v ]                    is c->k ( n/d --> n/d )
 
  [ k->r r->f ]                     is k->f ( n/d --> n/d )
  [ f->r r->k ]                     is f->k ( n/d --> n/d )
 
  [ r->k k->c ]                     is r->c ( n/d --> n/d )
  [ c->k k->r ]                     is c->r ( n/d --> n/d )
 
  [ f->k k->c ]                     is f->c ( n/d --> n/d )
  [ c->r r->f ]                     is c->f ( n/d --> n/d )
 
  [ $->v drop
         2dup 10 point$ echo$ 
    say " Kelvins is equal to" cr
    k->c 2dup 10 point$ echo$ 
    say " degrees Celcius"     cr
    c->f 2dup 10 point$ echo$ 
    say " degrees Fahrenheit"  cr
    f->r      10 point$ echo$ 
    say " degrees Rankine"     cr ] is task (   $ -->     )
 
  $ "21.00" task
Output:
21 Kelvins is equal to
-252.15 degrees Celcius
-421.87 degrees Fahrenheit
37.8 degrees Rankine


R

convert_Kelvin <- function(K){
    if (!is.numeric(K)) 
      stop("\n Input has to be numeric")
    
    return(list(
      Kelvin = K,
      Celsius = K - 273.15,
      Fahreneit = K * 1.8 - 459.67,
      Rankine = K * 1.8  
    ))
    
  }
  
  convert_Kelvin(21)
Output:
  $Kelvin
  [1] 21
  
  $Celsius
  [1] -252.15
  
  $Fahreneit
  [1] -421.87
  
  $Rankine
  [1] 37.8

Racket

Although not exactly the shortest code, the converter function can turn any temperature into any other

#lang racket
(define (converter temp init final)
  (define to-k
    (case init
      ('k temp)
      ('c (+ 273.15 temp))
      ('f (* (+ temp 459.67) 5/9))
      ('r (* temp 5/9))))
  (case final
    ('k to-k)
    ('c (- to-k 273.15))
    ('f (- (* to-k 9/5) 459.67))
    ('r (* to-k 1.8))))

(define (kelvin-to-all temp)
  (display (format "Kelvin: ~a \nCelsius: ~a \nFahrenheit: ~a \nRankine: ~a \n"
                   temp
                   (converter temp 'k 'c)
                   (converter temp 'k 'f)
                   (converter temp 'k 'r))))
(kelvin-to-all 21)
;Kelvin: 21 
;Celsius: -252.14999999999998 
;Fahrenheit: -421.87 
;Rankine: 37.800000000000004

Raku

(formerly Perl 6)

Translation of: Perl
my %scale =
    Celcius    => { factor => 1  , offset => -273.15 },
    Rankine    => { factor => 1.8, offset =>    0    },
    Fahrenheit => { factor => 1.8, offset => -459.67 },
;
 
my $kelvin = +prompt "Enter a temperature in Kelvin: ";
die "No such temperature!" if $kelvin < 0;
 
for %scale.sort {
    printf "%12s: %7.2f\n", .key, $kelvin * .value<factor> + .value<offset>;
}
Output:
Enter a temperature in Kelvin: 21
     Celcius: -252.15
  Fahrenheit: -421.87
     Rankine:   37.80

Alternative version that accepts the input in any of the four scales:

while my $answer = prompt 'Temperature: ' {
    my $k = do given $answer {
        when s/:i C $// { $_ + 273.15 }
        when s/:i F $// { ($_ + 459.67) / 1.8 }
        when s/:i R $// { $_ / 1.8 }
        when s/:i K $// { $_ }
        default         { $_ }
    }
    say "  { $k }K";
    say "  { $k - 273.15 }℃";
    say "  { $k * 1.8 - 459.67 }℉";
    say "  { $k * 1.8 }R";
}
Output:
Temperature: 0
  0K
  -273.15℃
  -459.67℉
  0R
Temperature: 0c
  273.15K
  0℃
  32℉
  491.67R
Temperature: 212f
  373.15K
  100℃
  212℉
  671.67R
Temperature: -40c
  233.15K
  -40℃
  -40℉
  419.67R

REXX

abridged

This REXX version supports:

  • (alternate spellings with optional   degree   or   degrees   preceding the scale name):
  • alternate temperature scale names
  • supports   any to all   conversions
  • supports   any to any   conversion   (with the   TO   option)
  • support of some common misspellings   (it knows what you mean)
  • support of some common temperature scales:
  • Celsius,   centigrade
  • Delisle
  • Fahrenheit
  • kelvin
  • Newton
  • Rankine
  • Reaumur,   Réaumur
  • Romer,   Rømer,   Roemer
  • multiple temperatures in a list
  • specification of which temperature scale to be used for conversion
  • conversion of a temperature to:
  • all other temperature scales
  • a specific temperature scale
  • supports proper pluralization of kelvin
  • comments (annotation notes) allowed within the list
  • aligned output (whole numbers and decimal fractions)
/*REXX program  converts  temperatures  for a number (8)  of  temperature scales.       */
numeric digits 120                               /*be able to support some huge numbers.*/
parse arg tList                                  /*get the specified temperature list.  */

  do  until  tList=''                            /*process the list of temperatures.    */
  parse  var tList  x  ','  tList                /*temps are separated by commas.       */
  x= translate(x, '((', "[{")                    /*support other grouping symbols.      */
  x= space(x);      parse var x z '('            /*handle any comments  (if any).       */
  parse upper  var  z  z   ' TO '  ! .           /*separate the  TO  option from number.*/
  if !==''  then != 'ALL';   all= !=='ALL'       /*allow specification of "TO" opt*/
  if z==''     then call serr "no arguments were specified."                 /*oops-ay. */
  _= verify(z, '+-.0123456789')                  /*list of valid numeral/number thingys.*/
  n= z
  if _\==0  then do
                 if _==1  then call serr 'illegal temperature:'   z
                 n= left(z,  _ - 1)              /*pick off the number  (hopefully).    */
                 u= strip( substr(z, _) )        /*pick off the  temperature  unit.     */
                 end
            else u= 'k'                          /*assume kelvin as per task requirement*/

  if \datatype(n, 'N')  then call serr 'illegal number:'    n
  if \all  then do                               /*is there is a     TO  ααα     scale? */
                call name !                      /*process the   TO   abbreviation.     */
                != sn                           /*assign the full name to     !        */
                end                              /*!: now contains temperature full name*/
  call name u                                    /*allow alternate scale (miss)spellings*/

      select                                     /*convert ──► °Fahrenheit temperatures.*/
      when sn=='CELSIUS'          then F= n       *  9/5   +  32
      when sn=='DELISLE'          then F= 212 -(n *  6/5)
      when sn=='FAHRENHEIT'       then F= n
      when sn=='KELVIN'           then F= n       *  9/5   - 459.67
      when sn=='NEWTON'           then F= n       * 60/11  +  32
      when sn=='RANKINE'          then F= n                - 459.67    /*a single  R  is taken as Rankine.*/
      when sn=='REAUMUR'          then F= n       *  9/4   +  32
      when sn=='ROMER'            then F= (n-7.5) * 27/4   +  32
      otherwise              call serr  'illegal temperature scale: '    u
      end   /*select*/

  K = (F + 459.67)  *  5/9                       /*compute temperature to  kelvins.     */
  say right(' ' x, 79, "─")                      /*show the original value, scale, sep. */
  if all | !=='CELSIUS'           then say $(   ( F   -  32     )   *  5/9           )    'Celsius'
  if all | !=='DELISLE'           then say $(   ( 212 -  F      )   *  5/6           )    'Delisle'
  if all | !=='FAHRENHEIT'        then say $(     F                                  )    'Fahrenheit'
  if all | !=='KELVIN'            then say $(        K                               )    'kelvin's(K)
  if all | !=='NEWTON'            then say $(   ( F   -  32     )   *  11/60         )    'Newton'
  if all | !=='RANKINE'           then say $(     F   + 459.67                       )    'Rankine'
  if all | !=='REAUMUR'           then say $(   ( F   -  32     )   *  4/9           )    'Reaumur'
  if all | !=='ROMER'             then say $(   ( F   -  32     )   *  4/27    + 7.5 )    'Romer'
  end   /*until*/

exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
s:    if arg(1)==1  then return arg(3);     return word( arg(2) 's',  1)
serr: say;   say '***error!***';    say;    say arg(1);    say;   exit 13
/*──────────────────────────────────────────────────────────────────────────────────────*/
$:    procedure;           showDig= 8            /*only show  eight  significant digits.*/
      _= format( arg(1), , showDig) / 1          /*format number 8 digs past dec, point.*/
      p= pos(., _);        L= length(_)          /*find position of the decimal point.  */
                                                 /* [↓]  align integers with FP numbers.*/
      if p==0  then _= _ || left('', 5+showDig+1)    /*the number has no decimal point. */
               else _= _ || left('', 5+showDig-L+p)  /* "     "    "   a    "      "    */
      return right(_, 50)                        /*return the re-formatted number (arg).*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
name: parse arg y                                       /*abbreviations  ──►  shortname.*/
      yU= translate(y, 'eE', "éÉ");       upper yU      /*uppercase the temperature unit*/
      if left(yU, 7)=='DEGREES'  then yU= substr(yU, 8) /*redundant "degrees" after  #? */
      if left(yU, 6)=='DEGREE'   then yU= substr(yU, 7) /*   "      "degree"    "    "  */
      yU= strip(yU)                                     /*elide blanks at front and back*/
      _= length(yU)                                     /*obtain the    yU    length.   */
      if right(yU,1)=='S' & _>1  then yU= left(yU, _-1) /*elide trailing plural, if any.*/

             select                                     /*abbreviations  ──►  shortname.*/
             when abbrev('CENTIGRADE' , yU)    |,
                  abbrev('CENTRIGRADE', yU)    |,                     /* 50% misspelled.*/
                  abbrev('CETIGRADE'  , yU)    |,                     /* 50% misspelled.*/
                  abbrev('CENTINGRADE', yU)    |,
                  abbrev('CENTESIMAL' , yU)    |,
                  abbrev('CELCIU'     , yU)    |,                     /* 82% misspelled.*/
                  abbrev('CELCIOU'    , yU)    |,                     /*  4% misspelled.*/
                  abbrev('CELCUI'     , yU)    |,                     /*  4% misspelled.*/
                  abbrev('CELSUI'     , yU)    |,                     /*  2% misspelled.*/
                  abbrev('CELCEU'     , yU)    |,                     /*  2% misspelled.*/
                  abbrev('CELCU'      , yU)    |,                     /*  2% misspelled.*/
                  abbrev('CELISU'     , yU)    |,                     /*  1% misspelled.*/
                  abbrev('CELSU'      , yU)    |,                     /*  1% misspelled.*/
                  abbrev('CELSIU'     , yU)       then sn= 'CELSIUS'
             when abbrev('DELISLE'    , yU,2)     then sn= 'DELISLE'
             when abbrev('FARENHEIT'  , yU)    |,                     /* 39% misspelled.*/
                  abbrev('FARENHEIGHT', yU)    |,                     /* 15% misspelled.*/
                  abbrev('FARENHITE'  , yU)    |,                     /*  6% misspelled.*/
                  abbrev('FARENHIET'  , yU)    |,                     /*  3% misspelled.*/
                  abbrev('FARHENHEIT' , yU)    |,                     /*  3% misspelled.*/
                  abbrev('FARINHEIGHT', yU)    |,                     /*  2% misspelled.*/
                  abbrev('FARENHIGHT' , yU)    |,                     /*  2% misspelled.*/
                  abbrev('FAHRENHIET' , yU)    |,                     /*  2% misspelled.*/
                  abbrev('FERENHEIGHT', yU)    |,                     /*  2% misspelled.*/
                  abbrev('FEHRENHEIT' , yU)    |,                     /*  2% misspelled.*/
                  abbrev('FERENHEIT'  , yU)    |,                     /*  2% misspelled.*/
                  abbrev('FERINHEIGHT', yU)    |,                     /*  1% misspelled.*/
                  abbrev('FARIENHEIT' , yU)    |,                     /*  1% misspelled.*/
                  abbrev('FARINHEIT'  , yU)    |,                     /*  1% misspelled.*/
                  abbrev('FARANHITE'  , yU)    |,                     /*  1% misspelled.*/
                  abbrev('FAHRENHEIT' , yU)       then sn= 'FAHRENHEIT'
             when abbrev('KALVIN'     , yU)    |,                     /* 27% misspelled.*/
                  abbrev('KERLIN'     , yU)    |,                     /* 18% misspelled.*/
                  abbrev('KEVEN'      , yU)    |,                     /*  9% misspelled.*/
                  abbrev('KELVIN'     , yU)       then sn= 'KELVIN'
             when abbrev('NEUTON'     , yU)    |,                     /*100% misspelled.*/
                  abbrev('NEWTON'     , yU)       then sn= 'NEWTON'
             when abbrev('RANKINE'    , yU, 1)    then sn= 'RANKINE'
             when abbrev('REAUMUR'    , yU, 2)    then sn= 'REAUMUR'
             when abbrev('ROEMER'     , yU, 2) |,
                  abbrev('ROMER'      , yU, 2)    then sn= 'ROMER'
             otherwise                call serr  'illegal temperature scale:'   y
             end   /*select*/
      return
output   when using the input of:     98.6F to C,   -40C, 0 c (water freezes),   37C (body temp),   100 C (water boils),   21 degrees Kelvin,   0 K (outer space?)
───────────────────────────────────────────────────────────────────  98.6F to C
                                  37               Celsius
─────────────────────────────────────────────────────────────────────────  -40C
                                 -40               Celsius
                                 210               Delisle
                                 -40               Fahrenheit
                                 233.15            kelvins
                                 -13.2             Newton
                                 419.67            Rankine
                                 -32               Reaumur
                                  -3.16666667      Romer
──────────────────────────────────────────────────────────  0 c (water freezes)
                                   0               Celsius
                                 150               Delisle
                                  32               Fahrenheit
                                 273.15            kelvins
                                   0               Newton
                                 491.67            Rankine
                                   0               Reaumur
                                   7.5             Romer
──────────────────────────────────────────────────────────────  37C (body temp)
                                  37               Celsius
                                  94.5             Delisle
                                  98.6             Fahrenheit
                                 310.15            kelvins
                                  12.21            Newton
                                 558.27            Rankine
                                  29.6             Reaumur
                                  17.36666667      Romer
──────────────────────────────────────────────────────────  100 C (water boils)
                                 100               Celsius
                                   0               Delisle
                                 212               Fahrenheit
                                 373.15            kelvins
                                  33               Newton
                                 671.67            Rankine
                                  80               Reaumur
                                  34.16666667      Romer
────────────────────────────────────────────────────────────  21 degrees Kelvin
                                -252.15            Celsius
                                 528.225           Delisle
                                -421.87            Fahrenheit
                                  21               kelvins
                                 -83.2095          Newton
                                  37.8             Rankine
                                -201.72            Reaumur
                                 -59.74            Romer
───────────────────────────────────────────────────────────  0 K (outer space?)
                                -273.15            Celsius
                                 559.725           Delisle
                                -459.67            Fahrenheit
                                   0               kelvins
                                 -90.1395          Newton
                                   0               Rankine
                                -218.52            Reaumur
                                 -65.34            Romer

[Actually, water freezes at 0.000089º C,   and boils at 99.974º C.]

unabridged

The REXX program can be seen at   ──►   Temperature conversion/REXX

This REXX version supports   58   temperature scales.

Scientific note:   at temperatures above   1 Planck,   quantum gravitational effects become relevant, and current physical theory breaks down because there is a lack of a theory of quantum gravity.


See the Wikipedia article:     Planck temperature.

output   when using the input of:     0 Fahrenheit
─────────────────────────────────────────────────────────────────  0 Fahrenheit
                                           255.37222222      Absolute
                                            47.67781999      Amonton
                                            -1               Barnsdorf
                                           -14.35292957      Beaumuir
                                           -21.81664121      Benart
                                           -23.8667          Bergen
                                           -15               Brisson
                                           -17.77777778      Celsius
                                             1.67777462      Cimento
                                           992.00031276      Cruquius
                                           -21.85185185      Dalence
                                           -21.57297438      Dalton
                                            -7.70075111      Daniell
                                             3               De la Hire
                                            -6.48011         De la Ville
                                           176.66666667      Delisle
                                           133.67787165      Delisle OLD
                                           -14               De Luc
                                           -17.5             De Lyon
                                           174.84536082      De Revillas
                                            72.4978          Derham
                                            -1.5             Derham OLD
                                           -23.7037          De Villeneuve
                                           -17.6666          De Suede
                                           -37.9202          Du Crest
                                             1.37508701      Edinburgh
                                             0.02200631      electron volts
                                             0               Fahrenheit
                                           -89.2727          Fahrenheit OLD
                                            -7.42857         Florentine large
                                           -73.9736          Florentine Magnum
                                             1.38571         Florentine small
                                           -83.97491258      Fowler
                                           -73.459919        Frick
                                           -10               gas mark
                                            16               Goubert
                                           -26.66666667      Hales
                                            10.000375        Hanow
                                          -122.44444444      Hauksbee
                                           210.7777          Jacobs-Holborn
                                           255.37222222      kelvins
                                           235.222           Leiden
                                            -5.86666667      Newton
                                            16               Oertel
                                             1.80241583E-30  Planck
                                           459.67            Rankine
                                           -14.22222222      Reaumur
                                             3.39999781      Richter
                                            -2.13333333      Rinaldini
                                             2.75925926      Romer
                                           866.84368889      Rosenthal
                                           122.82            Royal Society of London
                                            15.74512902      Segredo
                                           -44.20787188      Saint-Patrice
                                            -5.71111111      Stufe
                                           -29.00074174      Sulzer
                                            -0.59259259      Thermostat
                                           -11.53701838      Wedgwood
output   when using the input of:     0 kelvin
─────────────────────────────────────────────────────────────────────  0 kelvin
                                             0               Absolute
                                            -7.22722761      Amonton
                                           -68.03513851      Barnsdorf
                                          -220.52827751      Beaumuir
                                          -342.38766729      Benart
                                          -452.89203333      Bergen
                                          -230.4703125       Brisson
                                          -273.15            Celsius
                                          -168.14455975      Cimento
                                          -131.1567538       Cruquius
                                          -192.1             Dalence
                                           -infinity         Dalton
                                           -70.91221875      Daniell
                                          -249.38503119      De la Hire
                                          -459.51615256      De la Ville
                                           559.725           Delisle
                                           423.52554742      Delisle OLD
                                          -215.105625        De Luc
                                          -268.88203125      De Lyon
                                           553.95463918      De Revillas
                                          -104.21950913      Derham
                                          -154.72333333      Derham OLD
                                          -364.20011547      De Villeneuve
                                          -272.01733333      De Suede
                                          -337.00724352      Du Crest
                                           -97.38098225      Edinburgh
                                             0               electron volts
                                          -459.67            Fahrenheit
                                          -925.03633636      Fahrenheit OLD
                                          -401.43149281      Florentine large
                                          -766.5078253       Florentine Magnum
                                          -172.63202157      Florentine small
                                          -801.84922875      Fowler
                                          -650.345769        Frick
                                           -28.3868          gas mark
                                          -213.835           Goubert
                                          -409.725           Hales
                                          -420.93486331      Hanow
                                          -760.875           Hauksbee
                                        -1,602.36507778      Jacobs-Holborn
                                             0               kelvins
                                           -20.15022222      Leiden
                                           -90.1395          Newton
                                          -213.835           Oertel
                                             0               Planck
                                             0               Rankine
                                          -218.52            Reaumur
                                          -206.32443969      Richter
                                           -32.778           Rinaldini
                                           -65.34            Romer
                                           -11.63675556      Rosenthal
                                           757.1646          Royal Society of London
                                        -1,194.54976303      Segredo
                                          -219.57210928      Saint-Patrice
                                           -15.926           Stufe
                                          -430.12644531      Sulzer
                                            -9.105           Thermostat
                                           -21.81059691      Wedgwood

Ring

k = 21.0 c = 0 r = 0 f = 0
convertTemp(k)
see "Kelvin : " + k + nl +
"Celcius : " + c + nl +
"Rankine : " + r + nl +
"Fahrenheit : " + f + nl

func convertTemp k 
     c = k - 273.15
     r = k * 1.8
     f = r - 459.67

RPL

RPL has a built-in conversion feature with a convenient catalog of units.

≪ { "°C" "°F" "°R" } → tempk units 
 ≪ 1 3 FOR j 
      tempk "°K" units j GET CONVERT 
      SWAP →STR SWAP + 
   NEXT 
≫ ≫ 'K→CFR' STO
21 K→CFR
Output:
3:         "-252.15°C"
2:         "-421.87°F"
1:            "37.8°R"

Ruby

module TempConvert

  FROM_TEMP_SCALE_TO_K = 
  {'kelvin'     => lambda{|t| t},
   'celsius'    => lambda{|t| t + 273.15},
   'fahrenheit' => lambda{|t| (t + 459.67) * 5/9.0},
   'rankine'    => lambda{|t| t * 5/9.0},
   'delisle'    => lambda{|t| 373.15 - t * 2/3.0},
   'newton'     => lambda{|t| t * 100/33.0 + 273.15},
   'reaumur'    => lambda{|t| t * 5/4.0 + 273.15},
   'roemer'     => lambda{|t| (t - 7.5) * 40/21.0 + 273.15}}

  TO_TEMP_SCALE_FROM_K = 
  {'kelvin'     => lambda{|t| t},
   'celsius'    => lambda{|t| t - 273.15},
   'fahrenheit' => lambda{|t| t * 9/5.0 - 459.67},
   'rankine'    => lambda{|t| t * 9/5.0},
   'delisle'    => lambda{|t| (373.15 - t) * 3/2.0},
   'newton'     => lambda{|t| (t - 273.15) * 33/100.0},
   'reaumur'    => lambda{|t| (t - 273.15) * 4/5.0},
   'roemer'     => lambda{|t| (t - 273.15) * 21/40.0 + 7.5}}
  
  SUPPORTED_SCALES = FROM_TEMP_SCALE_TO_K.keys.join('|')

  def self.method_missing(meth, *args, &block)
    if valid_temperature_conversion?(meth) then
      convert_temperature(meth, *args)
    else
      super
    end
  end

  def self.respond_to_missing?(meth, include_private = false)
    valid_temperature_conversion?(meth) || super
  end
 
  def self.valid_temperature_conversion?(meth)
    !!(meth.to_s =~ /(#{SUPPORTED_SCALES})_to_(#{SUPPORTED_SCALES})/) 
  end
  
  def self.convert_temperature(meth, temp)
    from_scale, to_scale = meth.to_s.split("_to_")
    return temp.to_f if from_scale == to_scale # no kelvin roundtrip 
    TO_TEMP_SCALE_FROM_K[to_scale].call(FROM_TEMP_SCALE_TO_K[from_scale].call(temp)).round(2)
  end
 
end

Converts all eight scales to any other scale, by means of method_missing.

Usage:

TempConvert.kelvin_to_celsius 100 #=> -173.15
TempConvert.kelvin_to_fahrenheit 100 #=> -279.67
TempConvert.kelvin_to_rankine 100 #=> 180.0
TempConvert.kelvin_to_delisle 100 #=> 409.73
TempConvert.kelvin_to_newton 100 #=> -57.14
TempConvert.kelvin_to_reaumur 100 #=> -138.52
TempConvert.kelvin_to_roemer 100 #=> -83.4

TempConvert.newton_to_celsius 100 #=> 303.03
TempConvert.newton_to_fahrenheit 100 #=> 577.45
# All 64 combinations possible

Run BASIC

[loop]
input "Kelvin Degrees";kelvin
if kelvin <= 0 then end         ' zero or less ends the program
celcius     = kelvin - 273.15
fahrenheit  = kelvin * 1.8 - 459.67
rankine     = kelvin * 1.8
print kelvin;" kelvin is equal to ";celcius; " degrees celcius and ";fahrenheit;" degrees fahrenheit and ";rankine; " degrees rankine"
goto [loop]

Scala

Library: Scala
object TemperatureConversion extends App {

  def kelvinToCelsius(k: Double) = k + 273.15

  def kelvinToFahrenheit(k: Double) = k * 1.8 - 459.67

  def kelvinToRankine(k: Double) = k * 1.8

  if (args.length == 1) {
    try {
      val kelvin = args(0).toDouble
      if (kelvin >= 0) {
        println(f"K  $kelvin%2.2f")
        println(f"C  ${kelvinToCelsius(kelvin)}%2.2f")
        println(f"F  ${kelvinToFahrenheit(kelvin)}%2.2f")
        println(f"R  ${kelvinToRankine(kelvin)}%2.2f")
      } else println("%2.2f K is below absolute zero", kelvin)

    } catch {
      case e: NumberFormatException => System.out.println(e)
      case e: Throwable => {
        println("Some other exception type:")
        e.printStackTrace()
      }
    }
  } else println("Temperature not given.")
}
Output:
K  21,00
C  294,15
F  -421,87
R  37,80

Rust

fn main() -> std::io::Result<()> {
    print!("Enter temperature in Kelvin to convert: ");
    let mut input = String::new();
    std::io::stdin().read_line(&mut input)?;
    match input.trim().parse::<f32>() {
        Ok(kelvin) => {
            if kelvin < 0.0 {
                println!("Negative Kelvin values are not acceptable.");
            } else {
                println!("{} K", kelvin);
                println!("{} °C", kelvin - 273.15);
                println!("{} °F", kelvin * 1.8 - 459.67);
                println!("{} °R", kelvin * 1.8);
            }
        }

        _ => println!("Could not parse the input to a number."),
    }

    Ok(())
}

Scheme

(import (scheme base)
        (scheme read)
        (scheme write))

(define (kelvin->celsius k)
  (- k 273.15))

(define (kelvin->fahrenheit k)
  (- (* k 1.8) 459.67))

(define (kelvin->rankine k)
  (* k 1.8))

;; Run the program
(let ((k (begin (display "Kelvin    : ") (flush-output-port) (read))))
  (when (number? k)
    (display "Celsius   : ") (display (kelvin->celsius k)) (newline)
    (display "Fahrenheit: ") (display (kelvin->fahrenheit k)) (newline)
    (display "Rankine   : ") (display (kelvin->rankine k)) (newline)))
Output:
Kelvin    : 21
Celsius   : -252.14999999999998
Fahrenheit: -421.87
Rankine   : 37.800000000000004

Seed7

$ include "seed7_05.s7i";
  include "float.s7i";

const func float: celsius (in float: kelvin) is
  return kelvin - 273.15;

const func float: fahrenheit (in float: kelvin) is
  return kelvin * 1.8 - 459.67;

const func float: rankine (in float: kelvin) is
  return kelvin * 1.8;

const proc: main is func
  local
    var float: kelvin is 0.0;
  begin
    write("Enter temperature in kelvin: ");
    readln(kelvin);
    writeln("K: " <& kelvin             digits 2 lpad 7);
    writeln("C: " <& celsius(kelvin)    digits 2 lpad 7);
    writeln("F: " <& fahrenheit(kelvin) digits 2 lpad 7);
    writeln("R: " <& rankine(kelvin)    digits 2 lpad 7);
  end func;
Output:
Enter temperature in kelvin: 21.0
K:   21.00
C: -252.15
F: -421.87
R:   37.80

Sidef

Translation of: Perl
var scale = Hash(
    Celcius    => Hash.new(factor => 1  , offset => -273.15 ),
    Rankine    => Hash.new(factor => 1.8, offset =>    0    ),
    Fahrenheit => Hash.new(factor => 1.8, offset => -459.67 ),
);

var kelvin = Sys.readln("Enter a temperature in Kelvin: ").to_n;
kelvin >= 0 || die "No such temperature!";

scale.keys.sort.each { |key|
    printf("%12s:%8.2f\n", key, kelvin*scale{key}{:factor} + scale{key}{:offset});
}
Output:
Enter a temperature in Kelvin: 256
     Celcius:  -17.15
  Fahrenheit:    1.13
     Rankine:  460.80

Swift

func KtoC(kelvin : Double)->Double{
    
    return kelvin-273.15
}

func KtoF(kelvin : Double)->Double{
    
    return ((kelvin-273.15)*1.8)+32
}

func KtoR(kelvin : Double)->Double{
    
    return ((kelvin-273.15)*1.8)+491.67
}

var k// input
print("\(k) Kelvin")
var c=KtoC(kelvin : k)
print("\(c) Celsius")
var f=KtoF(kelvin : k)
print("\(f) Fahrenheit")
var r=KtoR(kelvin : k)
print("\(r) Rankine")

Tcl

proc temps {k} {
    set c [expr {$k - 273.15}]
    set r [expr {$k / 5.0 * 9.0}]
    set f [expr {$r - 459.67}]
    list $k $c $f $r
}


Demonstrating:

puts -nonewline "Enter a temperature in K: "
flush stdout
lassign [temps [gets stdin]] k c f r
puts [format "K: %.2f" $k]
puts [format "C: %.2f" $c]
puts [format "F: %.2f" $f]
puts [format "R: %.2f" $r]
Output:
Enter a temperature in K: 21
K: 21.00
C: -252.15
F: -421.87
R: 37.80

UNIX Shell

ksh

#!/bin/ksh
# Temperature conversion
set -A tt 0.00 273.15 373.15
for t in "${tt[@]}"
do
    echo
    echo "Kelvin:     $t K"
    echo "Celsius:    $((t-273.15)) C"
    echo "Fahrenheit: $((t*18/10-459.67)) F"
    echo "Rankine:    $((t*18/10)) R"
done

bash

Works with: Bourne Again SHell
#!/bin/bash
# Temperature conversion
tt[1]=0.00; tt[2]=273.15; tt[3]=373.15
for i in {1..3}
do
    t=${tt[$i]}
    echo $i
    echo "Kelvin:     $t K"
    echo "Celsius:    $(bc<<<"scale=2;$t-273.15") C"
    echo "Fahrenheit: $(bc<<<"scale=2;$t*18/10-459.67") F"
    echo "Rankine:    $(bc<<<"scale=2;$t*18/10") R"
done

Ursa

decl double k
while true
    out "Temp. in Kelvin? " console
    set k (in double console)
    out "K\t" k endl "C\t" (- k 273.15) endl console
    out "F\t" (- (* k 1.8) 459.67) endl "R\t" (* k 1.8) endl endl console
end while

VBA

Option Explicit

Sub Main_Conv_Temp()
Dim K As Single, Result As Single
    K = 21
    Debug.Print "Input in Kelvin      : " & Format(K, "0.00")
    Debug.Print "Output in Celsius    : " & IIf(ConvTemp(Result, K, "C"), Format(Result, "0.00"), False)
    Debug.Print "Output in Fahrenheit : " & IIf(ConvTemp(Result, K, "F"), Format(Result, "0.00"), False)
    Debug.Print "Output in Rankine    : " & IIf(ConvTemp(Result, K, "R"), Format(Result, "0.00"), False)
    Debug.Print "Output error         : " & IIf(ConvTemp(Result, K, "T"), Format(Result, "0.00"), False)
End Sub

Function ConvTemp(sngReturn As Single, Kelv As Single, InWhat As String) As Boolean
Dim ratio As Single
    
    ConvTemp = True
    ratio = 9 / 5
    Select Case UCase(InWhat)
        Case "C": sngReturn = Kelv - 273.15
        Case "F": sngReturn = (Kelv * ratio) - 459.67
        Case "R": sngReturn = Kelv * ratio
        Case Else: ConvTemp = False
    End Select
End Function
Output:
Input in Kelvin      : 21,00
Output in Celsius    : -252,15
Output in Fahrenheit : -421,87
Output in Rankine    : 37,80
Output error         : False

VBScript

WScript.StdOut.Write "Enter the temperature in Kelvin:"
tmp = WScript.StdIn.ReadLine

WScript.StdOut.WriteLine "Kelvin: " & tmp
WScript.StdOut.WriteLine "Fahrenheit: " & fahrenheit(CInt(tmp))
WScript.StdOut.WriteLine "Celsius: " & celsius(CInt(tmp))
WScript.StdOut.WriteLine "Rankine: " & rankine(CInt(tmp))

Function fahrenheit(k)
    fahrenheit = (k*1.8)-459.67
End Function

Function celsius(k)
    celsius = k-273.15
End Function

Function rankine(k)
    rankine = (k-273.15)*1.8+491.67
End Function
Output:
C:\>cscript /nologo tmp.vbs
Enter the temperature in Kelvin:21
Kelvin: 21
Fahrenheit: -421.87
Celsius: -252.15
Rankine: 37.8000000000001

Visual FoxPro

#DEFINE ABSZC 273.16
#DEFINE ABSZF 459.67
LOCAL k As Double, c As Double, f As Double, r As Double, n As Integer, ;
cf As String
n = SET("Decimals")
cf = SET("Fixed")
SET DECIMALS TO 2
SET FIXED ON
CLEAR
DO WHILE .T.
    k = VAL(INPUTBOX("Degrees Kelvin:", "Temperature"))
    IF k <= 0
    EXIT
    ENDIF   
    ? "K:", k
    c = k - ABSZC
    ? "C:", c
    f = 1.8*c + 32
    ? "F:", f
    r = f + ABSZF
    ? "R:", r
    ?
ENDDO   
SET FIXED &cf
SET DECIMALS TO n
Output:
K: 21.00
C: -252.15
F: -421.87
R: 37.80

V (Vlang)

Note: round_sig in 0.3 or later

import math

fn main() {
    c, f, r := kelvin_to_cfr(21)
    println('Celsius: $c˚\nFahrenheit: $f˚\nRankine: $r˚')
}

fn kelvin_to_cfr(kelvin f64) (string, string, string) {
    celsius := math.round_sig(kelvin - 273.15, 2)
    fahrenheit := math.round_sig(kelvin * 1.8 - 459.67, 2)
    rankine := math.round_sig(kelvin * 1.8, 2)
    return celsius.str(), fahrenheit.str(), rankine.str()
}
Output:
Celsius: -252.15˚
Fahrenheit: -421.87˚
Rankine: 38.80˚

Wren

Library: Wren-fmt
import "./fmt" for Fmt

var tempConv = Fn.new { |k|
    var c = k - 273.15
    var f = c * 1.8 + 32
    var r = f + 459.67
    System.print("%(Fmt.f(7, k, 2))˚ Kelvin")
    System.print("%(Fmt.f(7, c, 2))˚ Celsius")
    System.print("%(Fmt.f(7, f, 2))˚ Fahrenheit")
    System.print("%(Fmt.f(7, r, 2))˚ Rankine")
    System.print()
}

var ks = [0, 21, 100]
for (k in ks) tempConv.call(k)
Output:
   0.00˚ Kelvin
-273.15˚ Celsius
-459.67˚ Fahrenheit
   0.00˚ Rankine

  21.00˚ Kelvin
-252.15˚ Celsius
-421.87˚ Fahrenheit
  37.80˚ Rankine

 100.00˚ Kelvin
-173.15˚ Celsius
-279.67˚ Fahrenheit
 180.00˚ Rankine

XLISP

(DEFUN CONVERT-TEMPERATURE ()
    (SETQ *FLONUM-FORMAT* "%.2f")
    (DISPLAY "Enter a temperature in Kelvin.")
    (NEWLINE)
    (DISPLAY "> ")
    (DEFINE K (READ))
    (DISPLAY `(K = ,K))
    (NEWLINE)
    (DISPLAY `(C = ,(- K 273.15)))
    (NEWLINE)
    (DISPLAY `(F = ,(- (* K 1.8) 459.67)))
    (NEWLINE)
    (DISPLAY `(R = ,(* K 1.8))))
Output:
(CONVERT-TEMPERATURE)
Enter a temperature in Kelvin.
> 291.5
(K = 291.50)
(C = 18.35)
(F = 65.03)
(R = 524.70)

XPL0

include c:\cxpl\codes;
real K, C, F, R;
[ChOut(0, ^K);  K:= RlIn(0);
C:= K - 273.15;
ChOut(0, ^C);  RlOut(0, C);  CrLf(0);
F:= 1.8*C + 32.0;
ChOut(0, ^F);  RlOut(0, F);  CrLf(0);
R:= F + 459.67;
ChOut(0, ^R);  RlOut(0, R);  CrLf(0);
]
Output:
K 21
C -252.15000
F -421.87000
R   37.80000

zkl

K:=ask(0,"Kelvin: ").toFloat();
println("K %.2f".fmt(K));
println("F %.2f".fmt(K*1.8 - 459.67));
println("C %.2f".fmt(K - 273.15));
println("R %.2f".fmt(K*1.8));
Output:
Kelvin: 373.15
K 373.15
F 212.00
C 100.00
R 671.67