Pure Programmer
Blue Matrix


Cluster Map

Assertions

L1

This page is under construction. Please come back later.

Assertions1.cpp
#undef NDEBUG

#include "Utils.hpp"
#include <fmt/format.h>
#include <iostream>
#include <string>

using namespace std;

static double const TEST_BASE = 0.9;

double exponentiation(double base, int powerArg) noexcept {
	precondition(powerArg >= 0, "powerArg >= 0");
	int power = powerArg;
	double result = 1;
	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.
Assertions3.cpp
#undef NDEBUG

#include "Utils.hpp"
#include <fmt/format.h>
#include <iostream>
#include <string>

using namespace std;

static double const TEST_BASE = 0.9;

double exponentiation(double base, int powerArg) noexcept {
	precondition(powerArg >= 0, "exponentiation() power must be non-negative, was " + to_string(powerArg));
	int power = powerArg;
	double result = 1;
	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) ? result < 0 : result >= 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.
cpp

Questions

Projects

More ★'s indicate higher difficulty level.

References