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
- What section is listed as 2.7?ComputerScienceOne · Quadratic Roots
- What kinds of user input can cause problems in a quadratic-roots program?ComputerScienceOne · Computing Quadratic Roots
- How does the Java quadratic roots program check errors and calculate its roots?ComputerScienceOne · Quadratic Roots Revisited
- How can the return value communicate errors when roots are passed by reference?ComputerScienceOne · Quadratic Roots
- How does PHP compute the roots of a quadratic equation?ComputerScienceOne · Computing Quadratic Roots