Description
You are given a non-negative floating point number rounded to two decimal places celsius, that denotes the temperature in Celsius.
You should convert Celsius into Kelvin and Fahrenheit and return it as an array ans = [kelvin, fahrenheit].
Return the array ans. Answers within $10^{-5}$ of the actual answer will be accepted.
Note that:
Kelvin = Celsius + 273.15
Fahrenheit = Celsius * 1.80 + 32.00
Example
|
|
My thought process
I have no experience in creating arrays dynamically using malloc
and had to look up how to do it.
This is one of the examples from the book I was reading - “The C Programming Language” by Brian Kernighan and Dennis Ritchie.
Here is what I’ve done:
- I first created 2 variables of
double
data type to store the values of Kelvin and Fahrenheit. - Then I created a pointer to a double data type and allocated memory for it using
malloc
. - Using the Formula given, I calculated the values of Kelvin and Fahrenheit.
- I assigned the value of 2 to the returnSize pointer
- I then assigned the values of Kelvin and Fahrenheit to the array using the ans pointer.
- Lastly, I returned the ans pointer.
Java
I wanted to do this the easy way, calculating each of the values and assigning them to a variable, appending them to the array and returning the array at the end.
I soon realised that I was able to combine all these together by calculating the values in the array assignment statement.
I then returned the ans
array as my return value.
Code
C
|
|
{: file="Convert the temperature.c” }
The malloc function creates a size of $2\times$ the size of a double
data type to store both the values of Kelvin and Fahrenheit, this allows for dynamic allocation of memory.
Java
|
|
Afterthoughts
This program could probably be improved by directly assigning the ans pointer to the values of Kelvin and Fahrenheit during the calculation. This would reduce the number of lines of code and reduce the memory usage as lesser variables are created.
I need to have a better understanding of malloc
and its usage.
Java Implementation
I’ve done this in Java and it looks significantly easier without the manual dynamic allocation of array in C
.
I was able to do it by directly calculating the values in the array instead of assigning them to another variable first.