Concept
How does C handle arithmetic operators and integer division?
ComputerScienceOne / Operators
"15.4. Operators C supports the standard arithmetic operators for addition, subtraction, multiplication, and division using + , - , * , and / respectively. Each of these operators is a binary operator that acts on two operands which can be literals, variables or expressions and follow the usual rules of arithmetic when it comes to order of precedence (multiplication and division before addition and subtraction). 1 int a = 10, b = 20, c = 30, d; 2 d = a + 5; 3 d = a + b; 4 d = a - b; 5 d = a + b * c; 6 d = a * b; 7 d = a / b; //integer division and truncation! See below 8 9 double x = 1.5, y = 3.4, z = 10.5, w; 10 w = x + 5.0; 11 w = x + y; 12 w = x - y; 13 w = x + y * z; 14 w = x * y; 15 w = x / y; 16 17 //you can do arithmetic with both types: 18 w = a + x; 19 d = b + y; //truncation also occurs here! Special care must be taken when dealing with int types. For all four operators, if both operands are integers, the result will be an integer. For addition, subtraction, and multiplication this isn’t a big deal, but for division it means that when we divide, say 262"
Related Ideas
- How does Java handle arithmetic with wrapper classes?ComputerScienceOne · Operators
- Why does integer division truncate fractional results in C?ComputerScienceOne · Basic I/O
- How does Java’s integer remainder operator work?ComputerScienceOne · Basic I/O
- How do you use the C standard mathematics library?ComputerScienceOne · Preprocessor Directives
- How does PHP convert numeric strings during arithmetic operations?ComputerScienceOne · Type Juggling