From 2e778ff3f4ab75002c4edbca709e842c42c6c0c0 Mon Sep 17 00:00:00 2001 From: Tobias Berger Date: Tue, 21 Sep 2021 11:40:44 +0200 Subject: [PATCH] inv, more errors (for pow in future), toDouble and toFloat (untested) --- fraction.cpp | 6 ++++++ fraction.hpp | 11 +++++++---- tst_fractiontest.cpp | 21 ++++++++++++++++++++- 3 files changed, 33 insertions(+), 5 deletions(-) diff --git a/fraction.cpp b/fraction.cpp index 2a6c09d..51df04f 100644 --- a/fraction.cpp +++ b/fraction.cpp @@ -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; diff --git a/fraction.hpp b/fraction.hpp index ac988c4..6f6dcb1 100644 --- a/fraction.hpp +++ b/fraction.hpp @@ -3,10 +3,9 @@ #include 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; diff --git a/tst_fractiontest.cpp b/tst_fractiontest.cpp index 57fc24c..228f174 100644 --- a/tst_fractiontest.cpp +++ b/tst_fractiontest.cpp @@ -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"