Basics
As you might know, Americans measure the temperature in Fahrenheit. I'm not quite sure, but I guess the rest of the world uses Celsius.
0° C is the temperature when water freezes. 100° C is the temperature when water boils.
0° F is the lowest temperature of the winter 1708/1709 in Gdańsk. 32° F is the temperature when water boils.
If you want to calculate the temperature \(T_C\) in °C from \(T_F\) in °F you can use this formula: \(T_C = (T_F − 32) · \frac{5}{9}\)
The puzzle
What is the output of the following script?
public class test {
static double fahrenheitToCelsius(double fahrenheit) {
return (fahrenheit - 32) * (5 / 9);
}
public static void main(String[] args) {
double fahrenheit = 100;
double celsius = fahrenheitToCelsius(fahrenheit);
System.out.format("%.2f° Fahrenheit is %.2f° C\n",
fahrenheit, celsius);
fahrenheit = 30;
celsius = fahrenheitToCelsius(fahrenheit);
System.out.format("%.2f° Fahrenheit is %.2f° C\n",
fahrenheit, celsius);
}
}
. . . . . . . . . . . . . . . . . . . . . . . . .
Answer
100.00° Fahrenheit is 0.00° C
30.00° Fahrenheit is -0.00° C
Explanation
The problem is integer division.
public class test {
public static void main(String[] args) {
System.out.format("5 / 9 = %.2f\n", (double) (5 / 9));
}
}
This outputs:
5 / 9 = 0.00
So you are multiplying with \(\pm 0\) instead of \(0.55555\).