1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | #include <stdio.h>
#include <stdlib.h>
#include <assert.h>
// _pow(n, exponent) should return n^exponent, for exponent ≥ 1
int _pow(int n, int exponent) { // buggy power function
int result = 0; // BUG: 0→1 // *should* return n^exponent
for(int i = 0; i < exponent; i++) {
result *= n;
}
// Note: This is an extreme use of assert(…). Normally, you would
// have only 1-2 at a time.
//
// This demonstration was fleshing out different ways of expressing the
// "post-conditions" (things you expect to be true before program exits)
// using assert(…).
assert(! (n > 0 && result <= 0));
assert(! (n == 0 && result != 0));
assert(! (n < 0 && exponent % 2 == 0 && result < -n));
assert(! (n < 0 && exponent % 2 == 1 && result > n));
assert(! (exponent == 0 && n != 0 && result != 1));
assert((n > 0 && result >= n) ||
(n == 0 && result == 0) ||
(n < 0 && exponent % 2 == 0 && result >= -n) ||
(n < 0 && exponent % 2 == 1 && result <= n));
assert(! (result < n && n >= 0));
return result;
// OPTIONAL: For more on logic, see De Morgan's Laws
// https://en.wikipedia.org/wiki/De_Morgan%27s_laws
}
int main(int argc, char* argv[]) {
int n2 = _pow(5, 2);
printf("5 ^ 2 == %d\n", _pow(5, 2));
return EXIT_SUCCESS;
}
/* vim: set tabstop=4 shiftwidth=4 fileencoding=utf-8 noexpandtab: */
|
© Copyright 2019 Alexander J. Quinn This content is protected and may not be shared, uploaded, or distributed.