inv, more errors (for pow in future), toDouble and toFloat (untested)

This commit is contained in:
Tobias Berger 2021-09-21 11:40:44 +02:00
parent 912644d841
commit 2e778ff3f4
3 changed files with 33 additions and 5 deletions

View file

@ -70,6 +70,12 @@ namespace FractionNS {
QString Fraction::display() const {
return QString::number(m_numerator) + '/' + QString::number(m_denominator);
}
Fraction& Fraction::inv() const {
return *new Fraction(m_denominator, m_numerator);
}
float Fraction::toFloat() const { return float(m_numerator) / m_denominator; }
double Fraction::toDouble() const { return double(m_numerator) / m_denominator; }
bool Fraction::operator==(const int n) const {
return (double(m_numerator) / double(m_denominator)) == n;

View file

@ -3,10 +3,9 @@
#include <QString>
namespace FractionNS {
class divide_by_zero_error : public std::logic_error {
public:
divide_by_zero_error() : std::logic_error("tried to divide by zero") {};
};
struct divide_by_zero_error : public std::logic_error { divide_by_zero_error() : std::logic_error("tried to divide by zero") {}; };
struct not_real_error : public std::logic_error { not_real_error() : std::logic_error("value is not a real number") {}; };
struct not_defined_error : public std::logic_error { not_defined_error() : std::logic_error("operation result is not defined") {}; };
class Fraction
{
@ -26,6 +25,10 @@ namespace FractionNS {
void setDenominator(const int);
QString display() const;
Fraction& inv() const;
float toFloat() const;
double toDouble() const;
// Binary comparison operators
bool operator==(const int) const;

View file

@ -28,9 +28,12 @@ private slots:
void test_greater_than();
void test_less_than_or_equal();
void test_greater_than_or_equal();
void test_inverse();
};
FractionTest::FractionTest() {};
FractionTest::FractionTest() {
qDebug();
};
FractionTest::~FractionTest() {};
void FractionTest::test_constructor() {
@ -423,6 +426,22 @@ void FractionTest::test_greater_than_or_equal() {
}
void FractionTest::test_inverse() {
const Fraction f1 = Fraction(3, 2);
const Fraction f2 = Fraction(2, 3);
QCOMPARE(f1.inv(), f2);
QCOMPARE(f2.inv(), f1);
const Fraction f3 = Fraction(0, 2);
bool threw_divide_by_zero_error = false;
try {
f3.inv();
} catch (const divide_by_zero_error&) {
threw_divide_by_zero_error = true;
}
QVERIFY(threw_divide_by_zero_error);
}
QTEST_APPLESS_MAIN(FractionTest)
#include "tst_fractiontest.moc"