Bifalgorithm post · Computer science one · Basic I/O

Why does integer division truncate fractional results in C?

Why does integer division truncate fractional results in C? (Computer science one · Basic I/O) — "10 / 20, the result is not 0.5 as expected. The number 0.5 is…

Ideas in this flowchart

  • Conversión de tipos y truncamiento en operaciones numéricas de C
  • La división entre enteros trunca la parte fraccionaria del resultado.
  • En 10 / 20, el resultado es 0 en lugar de 0.5 porque 0.5 es un número de punto flotante y su parte fraccionaria se descarta.
  • Asignar un número de punto flotante a una variable int también trunca la parte fraccionaria.
  • En d = b + y, 20 + 3.4 produce 23.4, pero d recibe el valor entero 23.
  • Asignar un valor int a una variable double no causa problemas: 2 se convierte implícitamente en 2.0.
  • El casteo explícito puede forzar que al menos un operando de una división entera sea de tipo double.
  • La expresión x = (double) a / b produce el valor correcto de 0.5.
  • El casteo convierte temporalmente a en 10.0 para la división, evitando el truncamiento.
  • El operador % calcula el resto de dividir dos números enteros.
  • 10 % 5 produce 0.
  • 10 % 3 produce 1.
  • 29 % 5 produce 4.
Feed/

Why does integer division truncate fractional results in C?

No cover

Channel

Computer science one

1 page

"10 / 20, the result is not 0.5 as expected. The number 0.5 is a floating point number. As such, the fractional part gets truncated (cut off and thrown out) leaving only zero. In the code above, d = a / b; the variable d ends up getting the value zero because of this. Similarly, attempting to assign a floating point number to an integer also results in truncation because an int type cannot handle the fractional part. In the line d = b + y above, b + y correctly evaluates as 20 + 3.4 = 23.4, but when assigned to the int variable d the .4 gets truncated and d is assigned the value 23. Assigning an int value to a double variable is not a problem as the integer 2 implicitly becomes the floating point number 2.0. A solution to this problem is to use explicit type casting to force at least one of the operands in an integer division to become a double type. For example: 1 int a = 10, b = 20; 2 double x; 3 4 x = (double) a / b; results in x getting the “correct” value of 0.5. This works because the (double) code forces the int variable a to temporarily be treated as a double variable (in this case 10.0) for the purposes of division (so that truncation does not occur). C also supports the integer remainder operator using the % symbol. This operator gives the remainder of the result of dividing two integers. Examples: 1 int x; 2 3 x = 10 % 5; //x is 0 4 x = 10 % 3; //x is 1 5 x = 29 % 5; //x is 4"

Flowchart preview
👍
0
0 comments0 shares

Sign in to view and post comments.