Convert the Temperature
Problem
You are given a non-negative floating point number celsius (rounded to two decimals) that denotes a temperature in Celsius. Convert it into Kelvin and Fahrenheit and return the array ans = [kelvin, fahrenheit]. Answers within 10⁻⁵ of the actual answer are accepted.
The conversions are: Kelvin = Celsius + 273.15 and Fahrenheit = Celsius × 1.80 + 32.00.
celsius = 36.50[309.65000, 97.70000]def convertTemperature(celsius):
# Kelvin is an absolute shift of the Celsius scale.
kelvin = celsius + 273.15
# Fahrenheit scales by 1.80 and offsets by 32.00.
fahrenheit = celsius * 1.80 + 32.00
# Return both results in the required order.
return [kelvin, fahrenheit]
function convertTemperature(celsius) {
// Kelvin is an absolute shift of the Celsius scale.
const kelvin = celsius + 273.15;
// Fahrenheit scales by 1.80 and offsets by 32.00.
const fahrenheit = celsius * 1.80 + 32.00;
// Return both results in the required order.
return [kelvin, fahrenheit];
}
double[] convertTemperature(double celsius) {
// Kelvin is an absolute shift of the Celsius scale.
double kelvin = celsius + 273.15;
// Fahrenheit scales by 1.80 and offsets by 32.00.
double fahrenheit = celsius * 1.80 + 32.00;
// Return both results in the required order.
return new double[]{kelvin, fahrenheit};
}
vector<double> convertTemperature(double celsius) {
// Kelvin is an absolute shift of the Celsius scale.
double kelvin = celsius + 273.15;
// Fahrenheit scales by 1.80 and offsets by 32.00.
double fahrenheit = celsius * 1.80 + 32.00;
// Return both results in the required order.
return {kelvin, fahrenheit};
}
Explanation
This is a direct formula problem: there is no searching or looping, just two arithmetic conversions applied to the same input.
The Kelvin scale uses the same step size as Celsius but starts at absolute zero, so converting is a pure offset: Kelvin = Celsius + 273.15. Add the constant and you are done.
The Fahrenheit scale has a different step size, so the conversion both scales and offsets: Fahrenheit = Celsius × 1.80 + 32.00. Multiply first, then add 32.
We compute both values from the single celsius input and return them together as [kelvin, fahrenheit]. Because the judge accepts answers within 10⁻⁵, ordinary double-precision arithmetic is more than accurate enough.
Example: celsius = 36.50 gives 36.50 + 273.15 = 309.65 Kelvin and 36.50 × 1.80 + 32.00 = 97.70 Fahrenheit.