Code
Contracts and tests
Now every function gets a contract, and the program gets tests.
Contracts
#include <assert.h>at the top, first in the block of standard libraries.- Above each function a comment with "Before:" and "After:". If a function requires nothing (
is_validaccepts anyint), "After:" is enough. - The first line of
print_in_words:assert(is_valid(grade));.mainonly calls it with a checked grade, but if someone ever changesmain, theassertwill catch it.
A new function, round_to_int
int round_to_int(double x) {
assert(x >= 0);
return (int)(x + 0.5);
}
and one more line at the end of main: printf("Rounded: %d\n", round_to_int(average));.
Tests
A function run_tests with seven asserts, called as the first line of main. While all the tests pass they print nothing, and the program works as before.
Run it
The same input: 3, 9, 11, 4, 10. At the end you now get:
Average: 7.67
Rounded: 8
Break a test on purpose
Change one test so that it is wrong: assert(round_to_int(7.49) == 8);. Run the program and type anything:
Assertion failed: round_to_int(7.49) == 8, file C:/.../practice/05/main.c, line 66
Process finished with exit code 3
The program stopped before the first question, and the message says exactly which case doesn't work and on which line. Put == 7 back.
Commit: Add contracts and tests.