Concept
Why does integer division make the Fahrenheit-to-Celsius program produce zero?
ComputerScienceOne / Computing Quadratic Roots
"Examples use an ampersand when using scanf() : scanf(\"%lf\", &fahrenheit); We can now compute celsius using the formula provided: celsius = (fahrenheit - 32) * (5 / 9); Finally, we use printf() again to output the result to the user: printf(\"%f Fahrenheit is %f Celsius\n\n\", fahrenheit, celsius); 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. One 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. The full program can be found in Code Sample"
Related Ideas
- Why must you use floating-point division when converting Fahrenheit to Celsius in Java?ComputerScienceOne · Converting Units
- Why does integer division truncate fractional results in C?ComputerScienceOne · Basic I/O
- How does C handle arithmetic operators and integer division?ComputerScienceOne · Operators
- How do you outline a C program that converts Fahrenheit to Celsius?ComputerScienceOne · Converting Units
- How does scanf() read integer, character, and floating-point input in C?ComputerScienceOne · Basic I/O
- How can PHP convert a Fahrenheit temperature to Celsius?ComputerScienceOne · Converting Units
- How do you design a Java program that converts Fahrenheit to Celsius?ComputerScienceOne · Converting Units
- What C topics and example programs are listed in this excerpt?ComputerScienceOne · A simple program in C, resulting machine code formatted in hexadecimal