cint university / 101 / ced, the cint editor
101-02: arithmetic
This is lesson 101-02 of CU-101.2, checked against cint 0.2.0.
You will have the computer do arithmetic inside printed text, and find out what it does with a remainder.
the program
"minutes in a week: {7 * 24 * 60}\n";
"2 + 3 * 4 = {2 + 3 * 4}\n";
"(2 + 3) * 4 = {(2 + 3) * 4}\n";
"17 / 5 = {17 / 5}, remainder {17 % 5}\n";
"-17 / 5 = {-17 / 5}, remainder {-17 % 5}\n";
Run it:
minutes in a week: 10080
2 + 3 * 4 = 14
(2 + 3) * 4 = 20
17 / 5 = 3, remainder 2
-17 / 5 = -4, remainder 3
what happened
Braces make a hole in the text. cint works out what is inside { and } and prints the answer in its place. Outside the braces, 2 + 3 * 4 is printed just as it is written; inside them, it is worked out.
These signs are called operators. + adds, - subtracts and * multiplies. / divides and % gives the remainder of a division.
Multiplying and dividing come before adding and subtracting, as in school arithmetic. So 2 + 3 * 4 is 2 + 12, which is 14. Parentheses go first, so (2 + 3) * 4 is 5 * 4, which is 20.
Division gives a whole number. cint works with whole numbers only, so 17 / 5 is 3, not 3.4. % gives what is left over: 17 is three 5s and 2 more.
Division rounds down. The last line divides a negative number. On a number line, -17 divided by 5 is -3.4, and "down" means toward the left, so the answer is -4, not -3. The remainder is then 3, because five times -4 is -20, and -20 plus 3 is -17. For every division that gives an answer, the answer times the number you divided by, plus the remainder, gives back the number you started with.
-5 -4 -3 -2 -1 0
|------|------|------|------|------|
^
-3.4 rounds down to -4
change it
- Print how many hours are in a year of 365 days.
- Print how many days old you are, roughly: your age times 365.
- What is
100 / 7, and what is100 % 7? Check the rule from above: the answer times 7, plus the remainder, is 100.
answers
hours in a year: 8760
`100 / 7` is 14 and `100 % 7` is 2: 14 times 7 is 98, and 98 plus 2 is 100.
when it goes wrong
In school, many people write x for times. Try it:
"minutes in a week: {7 x 24 x 60}\n";
error[C1035]: invalid character or string literal
--> minutes.ci:1:22
|
1 | "minutes in a week: {7 x 24 x 60}\n";
| ^
|
The ^ points into the hole: what is inside the braces is not something cint can work out, because x is not an operator. Write * for times.