Beginner question.
This might be more of a math problem, I sorted the code out, but I have no idea why the solution works. Please help explain:
As you may know, the formula for coversion from Celsius to Farenheit is
F=C*9/5+32
Now, I am trying to write a simple Java code to do that conversion and I've defined the celsius and farenheit as double and also the final variable
final double MAGIC_NUMBER=9/5;
then calculated the conversion
farenheit=celsius*MAGIC_NUMBER+32;
The result was 24.0 celsius = 56.0 farenheit - which is not correct
I tried then defining the same thing in a different way:
final double MAGIC_NUMBER=1.8;
And the result was 24.0 celsius = 75.2 farenheit - which is the correct one. Now, 1.8 is the same thing as 9/5. Why did the second assign work and not the first one?
Here is the whole code:
package farenheit;
import java.util.Scanner;
public class Farenheit {
public static void main(String[] args) {
//declare variables
double celsius;
double farenheit;
final double MAGIC_NUMBER=1.8;
//prompt user to give me the temperature in celsius
Scanner in=new Scanner(System.in);
System.out.print("temperature in celsius= ");
celsius=in.nextDouble();
//calculate the conversion
farenheit=celsius*MAGIC_NUMBER+32;
//print out the result
System.out.printf("%.1f celsius = %.1f farenheit \n", celsius, farenheit);
}
}
Thanks!