Concept
Why must you use floating-point division when converting Fahrenheit to Celsius in Java?
ComputerScienceOne / Converting Units
"Try typing and running the program as defined above and you’ll find that you don’t get correct answers. In fact, you’ll find that no matter what values you enter, you get zero. This is because of the calculation using (5 / 9): recall what happens with integer division: truncation! This will always end up being zero.\n\nOne way we could fix it would be to pull out our calculators and find that 5/9 = 0.55555... and replace (5 / 9) with 0.555555. But, how many fives? It may be difficult to tell how accurate we can make this floating point number by hardcoding it ourselves. A much better approach would be to let the compiler take care of the optimal computation for us by making at least one of the numbers a double to prevent integer truncation. That is, we should instead use 5.0 / 9.\n\nThe full program can be found in Code Sample 26.3.\n\npackage unl.cse;\n\nimport java.util.Scanner;\n\npublic class TemperatureConverter {\n\npublic static void main(String args[]) {\n\ndouble fahrenheit, celsius;\n\nScanner s = new Scanner(System.in);\n\n//1. Prompt the user for input in Fahrenheit\n\nSystem.out.println(\"Please enter degrees in Fahrenheit: \");\n\n//2. Read the Fahrenheit value from the standard input\n\nfahrenheit = s.nextDouble();\n\n//3. Compute the degrees Celsius\n\ncelsius = (fahrenheit - 32) * 5.0 / 9;\n\n//4. Print the result to the user\n\nSystem.out.printf(\"%f Fahrenheit is %f Celsius\n\n\", fahrenheit, celsius);\n\n}\n\n}\n\nCode Sample 26.3.: Fahrenheit-to-Celsius Conversion Program in Java"
Related Ideas
- Why does integer division make the Fahrenheit-to-Celsius program produce zero?ComputerScienceOne · Computing Quadratic Roots
- How do you outline a C program that converts Fahrenheit to Celsius?ComputerScienceOne · Converting Units
- Why does integer division truncate fractional results in C?ComputerScienceOne · Basic I/O
- How can PHP convert a Fahrenheit temperature to Celsius?ComputerScienceOne · Converting Units
- How does C handle arithmetic operators and integer division?ComputerScienceOne · Operators
- How do you read numeric input from a user in Java with Scanner?ComputerScienceOne · Converting Units
- How are variables declared and assigned in Java?ComputerScienceOne · Declaration & Assignment
- What primitive types are available in Java?ComputerScienceOne · Declaration & Assignment