Drills: check yourself
Answer yourself first, only then open the answer.
1. What does this line print?
printf("%d %d %.1f\n", 7 / 2, 7 % 2, 7 / 2.0);
Answer
3 1 3.5
7 / 2: two ints, so 3. 7 % 2: the remainder, 1. 7 / 2.0: one side is a double, so 3.5.
2. Why doesn't this line build, and how do you fix it?
long long bytes = 3000000 * 1000;
Answer
3,000,000,000 doesn't fit in an int, and both numbers are ints, so the product overflows before it is stored in the long long: integer overflow in expression of type 'int'. The fix: 3000000LL * 1000.
3. What do you fix?
error: format '%c' expects argument of type 'int', but argument 2 has type 'char *' [-Werror=format=]
4 | printf("Group: PI25%c\n", "A");
Answer
"A" in double quotes is a string, and %c expects one character: 'A'.
4. What does it print?
printf("%d %d %d\n", (int)7.99, (int)(7.4 + 0.5), (int)(7.6 + 0.5));
Answer
7 7 8
(int) cuts the fraction off, it doesn't round: 7.99 becomes 7. Adding 0.5 rounds a positive number: 7.9 → 7, 8.1 → 8.
5. Which type of variable do you need?
a) a student's age
b) the average of grades
c) the population of the Earth (about 8,200,000,000)
d) the group letter
e) an item's price in cents
Answer
a) int, b) double, c) long long: more than INT_MAX (2,147,483,647), d) char, e) int: cents are a whole number, so there is no 0.1 + 0.2 problem.