Programs & Examples
Declarations and Initializations · Study material
Remainder and rounding of real numbers
The % operator needs integers, so the remainder of 3.14 / 2.1 comes from fmod(). To round 1.66 up to 2.0 use ceil(); round() also gives 2.0 here.
#include <math.h>
#include <stdio.h>
int main(void) {
printf("fmod(3.14, 2.1) = %.2f\n", fmod(3.14, 2.1)); /* % works only on integers */
printf("ceil %.1f, floor %.1f, round %.1f, trunc(-1.66) %.1f\n",
ceil(1.66), floor(1.66), round(1.66), trunc(-1.66));
return 0;
}
fmod(3.14, 2.1) = 1.04 ceil 2.0, floor 1.0, round 2.0, trunc(-1.66) -1.0
A zero-initialised table filled by a loop
= {0} guarantees that every cell the loop does not touch is zero – without it the unused cells would hold garbage.
#include <stdio.h>
int main(void) {
int t[4][4] = {0}; /* every element starts at 0 */
for (int r = 1; r <= 3; r++)
for (int c = 1; c <= 3; c++)
t[r][c] = r * c;
for (int r = 1; r <= 3; r++) {
for (int c = 1; c <= 3; c++)
printf("%3d", t[r][c]);
printf("\n");
}
printf("unused corner: %d\n", t[0][0] + t[3][0]);
return 0;
}
1 2 3 2 4 6 3 6 9 unused corner: 0