Temperature conversion: Difference between revisions

Content added Content deleted
(draft template)
(→‎{{header|D}}: added D)
Line 22: Line 22:


Write code that accepts a value of kelvin, converts it to values on the three other scales and prints the result. For instance:
Write code that accepts a value of kelvin, converts it to values on the three other scales and prints the result. For instance:
<pre>
K 21.00

C -252.15

F -421.87

R 37.80
</pre>

=={{header|D}}==
<lang d>import std.stdio, std.conv, std.string;

void main(string[] args) {
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);
}
}

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

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

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

unittest {
import std.math;
assert(approxEqual(kelvinToCelsius(21.0), -252.15));
assert(approxEqual(kelvinToFahrenheit(21.0), -421.87));
assert(approxEqual(kelvinToRankine(21.0), 37.8));
}</lang>
{{out}}
<pre>
<pre>
K 21.00
K 21.00