Assertions

This page is under construction. Please come back later.
#undef NDEBUG
#include "Utils.hpp"
#include <fmt/format.h>
#include <iostream>
#include <string>
using namespace Utils;
using namespace std;
static double const TEST_BASE = 0.9;
double exponentiation(double base, int power_arg) noexcept {
precondition(power_arg >= 0, "power_arg >= 0");
int power = power_arg;
double result = 1.0;
while (power > 0) {
result *= base;
--power;
}
return result;
}
int main(int argc, char **argv) {
for (int p = 10; p >= -1; --p) {
cout << fmt::format("{0:f} ^ {1:d} = {2:f}", TEST_BASE, p, exponentiation(TEST_BASE, p)) << endl;
}
return 0;
}
Output
$ g++ -std=c++17 Assertions1.cpp -o Assertions1 -lfmt
$ ./Assertions1
0.900000 ^ 10 = 0.348678
0.900000 ^ 9 = 0.387420
0.900000 ^ 8 = 0.430467
0.900000 ^ 7 = 0.478297
0.900000 ^ 6 = 0.531441
0.900000 ^ 5 = 0.590490
0.900000 ^ 4 = 0.656100
0.900000 ^ 3 = 0.729000
0.900000 ^ 2 = 0.810000
0.900000 ^ 1 = 0.900000
0.900000 ^ 0 = 1.000000
Precondition failed: powerArg >= 0, File: Assertions1.cpp Line: 13.
#undef NDEBUG
#include "Utils.hpp"
#include <fmt/format.h>
#include <iostream>
#include <string>
using namespace Utils;
using namespace std;
static double const TEST_BASE = 0.9;
double exponentiation(double base, int power_arg) noexcept {
precondition(power_arg >= 0, string("exponentiation() power must be non-negative, was ") + to_string(power_arg));
int power = power_arg;
double result = 1.0;
while (power > 0) {
result *= base;
--power;
}
// This line will make the result incorrect.
result = -result;
// If power is odd and base is negative, then result should be negative.
// Otherwise result should be positive.
postcondition((power & 1) == 1 && (base < 0.0) ? result < 0.0 : result >= 0.0, "Postcondition Failed: Result is wrong sign");
return result;
}
int main(int argc, char **argv) {
for (int p = 10; p >= -1; --p) {
cout << fmt::format("{0:f} ^ {1:d} = {2:f}", TEST_BASE, p, exponentiation(TEST_BASE, p)) << endl;
}
return 0;
}
Output
$ g++ -std=c++17 Assertions3.cpp -o Assertions3 -lfmt
$ ./Assertions3
Postcondition failed: Postcondition Failed: Result is wrong sign, File: Assertions3.cpp Line: 24.
Questions
- {{Who's on first?}}
- {{Who's on second?}}
- {{Who's on third?}}
Projects
More ★'s indicate higher difficulty level.
- Base Conversion
- Fast Exponentiation
- Fibonacci Numbers with Memoization
- Football Passer Rating (with Assertions)
- Julian Day Number
- Number of Primes (Estimate)
- Ordinal Date
- Ordinal Date (Revisited)
- Shuffle Deck
- Significant Digits
References
-
[[C++ Programming Language]], 4th Edition, Bjarne Stroustrup, Addison-Wesley, 2013, ISBN 978-0321563842.
- [[C++ Language Reference]]
- [[cplusplus.com]]
- [[Cprogramming.com]]
Pure Programmer


