Bifalgorithm post · Computer science one · Computing Quadratic Roots

Why does integer division make the Fahrenheit-to-Celsius program produce zero?

Why does integer division make the Fahrenheit-to-Celsius program produce zero? (Computer science one · Computing Quadratic Roots) — "Examples use an ampersand…

Ideas in this flowchart

  • Cálculo de Celsius a partir de Fahrenheit y corrección de la división entera
  • scanf() usa un ampersand para almacenar la entrada en fahrenheit: scanf("%lf", &fahrenheit);
  • La temperatura Celsius se calcula con celsius = (fahrenheit - 32) * (5 / 9);
  • printf() muestra al usuario los valores de Fahrenheit y Celsius.
  • El programa produce cero para cualquier valor introducido.
  • La expresión 5 / 9 usa división entera, que trunca el resultado a cero.
  • Una solución posible es reemplazar 5 / 9 por una aproximación como 0.555555.
  • Es difícil determinar cuántos decimales hacen suficientemente precisa una constante escrita manualmente.
  • Es mejor hacer que al menos uno de los números sea double para evitar la truncación entera.
  • La expresión corregida es 5.0 / 9.
  • El programa completo se encuentra en el ejemplo de código.
Feed/

Why does integer division make the Fahrenheit-to-Celsius program produce zero?

No cover

Channel

Computer science one

1 page

"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"

Flowchart preview
👍
0
0 comments0 shares

Sign in to view and post comments.