Temperature conversion: Difference between revisions
No edit summary |
(Pure Data -- picture upload would result in much better comprehension!) |
||
Line 1,343: | Line 1,343: | ||
0.00 CELSIUS -> 32.00 FAHRENHEIT |
0.00 CELSIUS -> 32.00 FAHRENHEIT |
||
37.00 CELSIUS -> 98.60 FAHRENHEIT |
37.00 CELSIUS -> 98.60 FAHRENHEIT |
||
</pre> |
</pre> |
||
=={{header|Pure Data}}== |
|||
'''temperature.pd''' |
|||
<pre> |
|||
#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; |
|||
</pre> |
|||
Plugin to round the results to at most 2 digits: |
|||
'''+rnd.pd''' |
|||
<pre> |
|||
#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; |
|||
</pre> |
|||
=={{header|Python}}== |
=={{header|Python}}== |
Revision as of 11:50, 23 January 2014
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 4 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.
Write code that accepts a value of kelvin, converts it to values on the three other scales and prints the result. For instance:
K 21.00 C -252.15 F -421.87 R 37.80
Ada
<lang 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;</lang>
- Output:
21.0 K: 21.00 C: -252.15 F: -421.87 R: 37.80
Aime
<lang 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;
}</lang>
- Output:
aime$ aime -a tmp/tconvert 300 K 300 C 26.85 F 80.32 R 540
AutoHotkey
<lang 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)
}</lang>
- Output:
Kelvin: 21.00 K Celsius: -252.15 C Fahrenheit: -421.87 F Rankine: 37.80 R
AWK
<lang AWK># 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)
}</lang>
BASIC
<lang 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 </lang>
BASIC256
<lang 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) </lang>
BBC BASIC
<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 </lang> Output:
Kelvin degrees (>=0): 21 K = 21.00 C = -252.15 F = -421.87 R = 37.80
Bracmat
<lang 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! )</lang> Output:
Enter Kelvin temperature:21.00 21.00 K -252.15 °C -421.87 °F 37.80 °Ra -201.72 °Ré
C
<lang 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;
}</lang>
C++
<lang cpp>
- 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;
} //-------------------------------------------------------------------------------------------------- </lang> 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
COBOL
<lang 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 .</lang>
- Output:
Enter a temperature in Kelvin to convert: 21 K 21.00 C -252.15 F -421.88 R 37.79
D
<lang 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); }
}</lang>
- Output:
K 21.00 C -252.15 F -421.87 R 37.80
Erlang
<lang 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 . </lang>
- Output:
K : 21.0 C : -252.15 F : -421.87 R : 37.8 ok
Ezhil
<lang 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 </lang>
F#
<lang fsharp> // 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) </lang>
Go
<lang 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)
}</lang>
- Output:
> k 21 K 21.00 C -252.15 F -421.87 R 37.80
Icon and Unicon
The following program works in both languages: <lang unicon>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</lang>
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 ->
J
Solution:<lang j> 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./ ]</lang>
- Example:
<lang j> NB. Format matrix for printing
fmt =: '0.2' 8!:0 k2KCFR
NB. Tag each temp with scale, for human NB. legibility. kcfr =: 0 _1 |: 'KCFR' ,"0 1"_1 >@:fmt 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 C-252.00 F-421.87 R 37.80
K 100.00 C-173.00 F-279.67 R 180.00
K 300.00 C 27.00 F 80.33 R 540.00</lang> 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
<lang 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; }
}</lang>
- Output:
K 21.00 C -252.15 F -421.87 R 37.80
Julia
<lang 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))")</lang>
julia> cfr(21) Kelvin: 21, Celsius: -252.15, Fahrenheit: -421.87, Rankine: 37.8
Lasso
<lang 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')
'
'
tempconverter(21, 'c')
'
'
tempconverter(-41, 'c')
'
'
tempconverter(37.80, 'r')
'
'
tempconverter(69.80, 'f')</lang>
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
Mathematica
<lang Mathematica>tempConvert[t_] := Grid[Transpose@{{"K", "C", "F", "R"}, Round[{t, t - 273.15, 9 t/5 - 459.67, 9 t/5}, .01]}]
tempConvert[21]</lang>
- Output:
K 21. C -252.15 F -421.87 R 37.8
МК-61/52
<lang mk61>П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</lang>
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.
NetRexx
<lang 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
</lang>
- 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
Objeck
<lang 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; }
} </lang>
K: 21.0 C: -252.150 F: -421.870 R: 37.800
Objective-C
<lang objc>#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;
}</lang>
PARI/GP
<lang parigp>f(x)=[x,x-273.15,1.8*x-459.67,1.8*x]</lang>
Perl
<lang Perl>#!/usr/bin/perl use strict ; use warnings ;
sub kelvin_to_other_scales {
my $kelvin = shift ; my $celsius = $kelvin - 273.15 ; my $rankine = 9 * $kelvin / 5 ; my $fahrenheit = $rankine - 459.67 ; my @scales ; push @scales , $kelvin , $celsius , $fahrenheit , $rankine ; return @scales ;
}
print "Enter a temperature in Kelvin: " ; my $kelvin = <STDIN> ; chomp $kelvin ; while ( $kelvin < 0 ) {
print "Error! There are no negative kelvin degrees!\n" ; $kelvin = <STDIN> ; chomp $kelvin ;
} my @scales = kelvin_to_other_scales( $kelvin ) ; print "K $scales[ 0 ]\n" ; print "C $scales[ 1 ]\n" ; print "F $scales[ 2 ]\n" ; print "R $scales[ 3 ]\n" ;</lang>
- Output:
Enter a temperature in Kelvin: 21 K 21 C -252.15 F -421.87 R 37.8
Perl 6
<lang perl6>while ne 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";
}</lang>
- 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
PHP
<lang php>error_reporting(E_ALL & ~ ( E_NOTICE | E_WARNING ));
while (true) {
echo "\nEnter a value in kelvin (q to quit): "; if (($kelvin = trim(fgets(STDIN))) !== false) { 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); } }
}</lang>
- 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
<lang 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) ) ) )</lang>
Test: <lang PicoLisp>(convertKelvin 21.0)</lang> Output:
K 21.00 C -252.15 F -421.87 R 37.80
PL/I
<lang pli>*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;</lang>
Output (sample):
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
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
<lang 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 ? </lang>
Python: Universal conversion
This converts from any one of the units to all the others <lang python>>>> 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> ? </lang>
Racket
Althoguh not exactly the shortest code, the converter function can turn any temperature into any other <lang Racket>#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
</lang>
REXX
This REXX version supports:
- (alternate spellings with optional degree or degrees preceding the scale name):
- centigrade, centingrade, centesimal, Celsius, and some misspellings
- Delisle
- Fahrenheit, and some misspellings
- Kelvin, and some misspellings
- Newton, and a misspelling
- Rankine
- Reaumur, Réaumur
- Romer (Rømer), Roemer
- multiple temperatures in a list
- specification of which temperature to be used for conversion
- conversion of a temperature to all eight temperatures
- comments within the list
- aligned output (whole numbers and decimal fractions)
<lang rexx>/*REXX program converts temperature for: C, D, F, N, Ra, Re, Ro, and K.*/ parse arg tList /*get specified temperature lists*/
do until tList= /*process a 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). */ if z== then call serr 'no arguments were specified.' _=verify(z, '+-.0123456789') /*a list of valid 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 req.*/
uU=translate(u,'eE',"éÉ"); upper uU /*uppercase version of temp unit.*/ if left(uU,7)=='DEGREES' then uU=substr(uU,8) /*redundant "degrees"? */ if left(uU,6)=='DEGREE' then uU=substr(uU,7) /* " "degree" ? */ uU=strip(uU) if \datatype(n,'N') then call serr 'illegal number:' n /*accept alternate spellings. */ select /*convert ──► ºF temperatures. */ when abbrev('CENTIGRADE' , uU) |, abbrev('CENTRIGRADE', uU) |, /* 50% misspelled.*/ abbrev('CETIGRADE' , uU) |, /* 50% misspelled.*/ abbrev('CENTINGRADE', uU) |, abbrev('CENTESIMAL' , uU) |, abbrev('CELCIUS' , uU) |, /* 82% misspelled.*/ abbrev('CELCIOUS' , uU) |, /* 4% misspelled.*/ abbrev('CELCUIS' , uU) |, /* 4% misspelled.*/ abbrev('CELSUIS' , uU) |, /* 2% misspelled.*/ abbrev('CELCEUS' , uU) |, /* 2% misspelled.*/ abbrev('CELCUS' , uU) |, /* 2% misspelled.*/ abbrev('CELISUS' , uU) |, /* 1% misspelled.*/ abbrev('CELSUS' , uU) |, /* 1% misspelled.*/ abbrev('CELSIUS' , uU) then F=n * 9/5 + 32
when abbrev('DELISLE' , uU) then F=212 -(n * 6/5)
when abbrev('FARENHEIT' , uU) |, /* 39% misspelled.*/ abbrev('FARENHEIGHT', uU) |, /* 15% misspelled.*/ abbrev('FARENHITE' , uU) |, /* 6% misspelled.*/ abbrev('FARENHIET' , uU) |, /* 3% misspelled.*/ abbrev('FARHENHEIT' , uU) |, /* 3% misspelled.*/ abbrev('FARINHEIGHT', uU) |, /* 2% misspelled.*/ abbrev('FARENHIGHT' , uU) |, /* 2% misspelled.*/ abbrev('FAHRENHIET' , uU) |, /* 2% misspelled.*/ abbrev('FERENHEIGHT', uU) |, /* 2% misspelled.*/ abbrev('FEHRENHEIT' , uU) |, /* 2% misspelled.*/ abbrev('FERENHEIT' , uU) |, /* 2% misspelled.*/ abbrev('FERINHEIGHT', uU) |, /* 1% misspelled.*/ abbrev('FARIENHEIT' , uU) |, /* 1% misspelled.*/ abbrev('FARINHEIT' , uU) |, /* 1% misspelled.*/ abbrev('FARANHITE' , uU) |, /* 1% misspelled.*/ abbrev('FAHRENHEIT' , uU) then F=n
when abbrev('KELVINS' , uU) |, /* 46% misspelled.*/ abbrev('KALVIN' , uU) |, /* 27% misspelled.*/ abbrev('KERLIN' , uU) |, /* 18% misspelled.*/ abbrev('KEVEN' , uU) |, /* 9% misspelled.*/ abbrev('KELVIN' , uU) then F=n * 9/5 - 459.67
when abbrev('NEUTON' , uU) |, /*100% misspelled.*/ abbrev('NEWTON' , uU) then F=n * 60/11 + 32
/*a single R is taken as Rankine.*/ when abbrev('RANKINE' , uU) then F=n - 459.67
when abbrev('REAUMUR' , uU, 2) then F=n * 9/4 + 32
when abbrev('ROEMER' , uU, 2) |, abbrev('ROMER' , uU, 2) then F=(n-7.5) * 27/4 + 32 otherwise call serr 'illegal temperature scale:' u end /*select*/
say right(' ' x,55,"─") /*show original value&scale, sep.*/ say Tform( ( F - 32 ) * 5/9 ) 'Celsius' say Tform( ( 212 - F ) * 5/6 ) 'Delisle' say Tform( F ) 'Fahrenheit' say Tform( ( F + 459.67 ) * 5/9 ) 'Kelvin' say Tform( ( F - 32 ) * 11/60 ) 'Newton' say Tform( F + 459.67 ) 'Rankine' say Tform( ( F - 32 ) * 4/9 ) 'Reaumur' say Tform( ( F - 32 ) * 7/24 + 7.5 ) 'Romer' end /*until tlist= */
exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────TFORM subroutine────────────────────*/ Tform: procedure; showDig=8 /*only show 8 significant digits.*/ _=format(arg(1),,showDig)/1 /*format arg 8 digs past the . */ p=pos('.',_) /*find position of decimal point.*/
/* [↓] align integers with FP #s.*/
if p==0 then _=_ || left(,showDig+1) /*no decimal point.*/
else _=_ || left(,showDig-length(_)+p) /*has " " */
return right(_,20) /*return the re-formatted arg. */ /*──────────────────────────────────SERR subroutine─────────────────────*/ serr: say; say '***error!***'; say; say arg(1); say; exit 13</lang> output when using the input of: -40C, 0 c (water freezes), 37C (body temp), 100 C (water boils), 21 degrees Kelvin, 0K (outer space?)
───────────────────────────────────────────────── -40C -40 Celsius 210 Delisle -40 Fahrenheit 233.15 Kelvin -13.2 Newton 419.67 Rankine -32 Reaumur -13.5 Romer ────────────────────────────────── 0 c (water freezes) 0 Celsius 150 Delisle 32 Fahrenheit 273.15 Kelvin 0 Newton 491.67 Rankine 0 Reaumur 7.5 Romer ────────────────────────────────────── 37C (body temp) 37 Celsius 94.5 Delisle 98.6 Fahrenheit 310.15 Kelvin 12.21 Newton 558.27 Rankine 29.6 Reaumur 26.925 Romer ────────────────────────────────── 100 C (water boils) 100 Celsius 0 Delisle 212 Fahrenheit 373.15 Kelvin 33 Newton 671.67 Rankine 80 Reaumur 60 Romer ──────────────────────────────────── 21 degrees Kelvin -252.15 Celsius 528.225 Delisle -421.87 Fahrenheit 21 Kelvin -83.2095 Newton 37.8 Rankine -201.72 Reaumur -124.87875 Romer ──────────────────────────────────── 0K (outer space?) -273.15 Celsius 559.725 Delisle -459.67 Fahrenheit 0 Kelvin -90.1395 Newton 0 Rankine -218.52 Reaumur -135.90375 Romer
[Actually, water freezes at 0.000089º C, and boils at 99.974º C.]
Ruby
<lang 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</lang> Converts all eight scales to any other scale, by means of method_missing. Usage: <lang ruby>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</lang>
Run BASIC
<lang runbasic>[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]</lang>
Seed7
<lang 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;</lang>
- Output:
Enter temperature in kelvin: 21.0 K: 21.00 C: -252.15 F: -421.87 R: 37.80
Tcl
<lang 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
}</lang> Demonstrating: <lang tcl>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]</lang>
- Output:
Enter a temperature in K: 21 K: 21.00 C: -252.15 F: -421.87 R: 37.80
XPL0
<lang 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); ]</lang>
- Output:
K 21 C -252.15000 F -421.87000 R 37.80000
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>
- Programming Tasks
- Solutions by Programming Task
- Ada
- Aime
- AutoHotkey
- AWK
- BASIC
- BASIC256
- BBC BASIC
- Bracmat
- C
- C++
- COBOL
- D
- Erlang
- Ezhil
- F Sharp
- Go
- Icon
- Unicon
- J
- Java
- Julia
- Lasso
- Mathematica
- МК-61/52
- NetRexx
- Objeck
- Objective-C
- PARI/GP
- Perl
- Perl 6
- PHP
- PicoLisp
- PL/I
- Pure Data
- Python
- Racket
- REXX
- Ruby
- Run BASIC
- Seed7
- Tcl
- XPL0
- ZX Spectrum Basic
- Lilypond/Omit