Concept
Why does integer division truncate fractional results in C?
ComputerScienceOne / Basic I/O
"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"
Related Ideas
- How does C handle arithmetic operators and integer division?ComputerScienceOne · Operators
- Why does integer division make the Fahrenheit-to-Celsius program produce zero?ComputerScienceOne · Computing Quadratic Roots
- How does Java’s integer remainder operator work?ComputerScienceOne · Basic I/O
- Why must you use floating-point division when converting Fahrenheit to Celsius in Java?ComputerScienceOne · Converting Units
- What primitive types does C support?ComputerScienceOne · Declaration & Assignment
- How does the modulo operator calculate remainders in PHP?ComputerScienceOne · Type Juggling
- How can you convert a decimal number to hexadecimal using modulo and floor?Stephen Davies, Ph.D. Version 2.2.2 Through Discrete Mathematics A Cool Brisk Walk · Chapter 1
- What is 17?ComputerScienceOne · Normalizing a Number