A visual guide to C's arithmetic operators (+, -, *, /, %), implicit type conversion, and casts.
+ - * / for arithmetic, % for remainder*// bind tighter than +/-( ) to override precedence7/2 is 3, not 3.5.int and double, the int is automatically promoted to double. That's implicit conversion.int a = 7; double b = 2.0; double result = a / b; // a is auto-promoted to double β 7.0 / 2.0 = 3.5
double, the result is a double. Only when both sides are int do you get integer (truncated) division.(target type) in front of an expression temporarily converts it to that type. This is called a cast.int a = 7, b = 2; // No cast β integer division printf("%d\n", a / b); // 3 (truncated) // With cast β floating-point printf("%f\n", (double)a / b); // 3.500000
(type) expressionint x = 5; double d = (double)x; // 5.0
double d = 3.7; int n = (int)d; // 3 (fractional part truncated)
int sum = 17, n = 3; double avg = (double)sum / n; // 5.666...
(double)(sum / n) does the integer division first (sum / n = 5), then casts the 5 to 5.0.| Situation | Code | Why |
|---|---|---|
| Integer division, but you want a float result | (double)a / b | Make one side a double to force floating-point division |
| Computing an average | (double)sum / count | Avoid int / int truncation |
| malloc's return value | (int *)malloc(...) | Convert void* to the appropriate pointer type |
| Truncate a float toward zero | (int)3.7 β 3 | Drop the fractional part |
| Treat a char as a number | (int)'A' β 65 | Get the ASCII code |
int a = 10, b = 3; printf("A: %d\n", a / b); printf("B: %f\n", (double)a / b); printf("C: %f\n", (double)(a / b));
int / int = int β 10/3 = 3 (truncated).(double)a / b β 10.0 / 3 = 3.333333 (cast happens before the division, so it's floating-point).(double)(a / b) β (double)(3) = 3.000000 (integer division happens first β the position of the cast really matters!)
% (remainder) to test whether a number is even or odd7/2 truncates to 3 when both operands are intdoubleCheck your understanding of this lesson!
int / int drops the fractional part, so 7 / 2 = 3.
% is the modulo (remainder) operator. 7 / 2 is 3 remainder 1, so the result is 1.
Casting to (double) forces floating-point division: 5.0 / 2 = 2.5.