Добавил:
CanyonE
СПбГУТ * ИКСС * Программная инженерия
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз:
Предмет:
Файл:Решения лабораторных работ (местами есть ошибки) / Lab1_Floating point numbers
.cpp#include <iostream>
#include <stdexcept>
using std::cin;
using std::cout;
using std::endl;
// Класс «Число с плавающей точкой (запятой)»
template <long E>
class Real {
private:
static const long factor_ = 1 << ( E - 1 );
long m_;
public:
// Конструктор
explicit Real(long m = 0) : m_(m) {}
explicit Real(double d = 0) : m_(long(d * factor_)) {}
// Сложение
Real operator+(const Real &arg) const { return Real(m_ + arg.m_); }
// Вычитание
Real operator-(const Real &arg) const { return Real(m_ - arg.m_); }
// Смена знака
Real operator-() const { return Real(-m_); }
// Умножение
Real operator*(const Real &arg) const { return Real(( m_ * arg.m_ ) >> E); }
// Деление
Real operator/(const Real &arg) const { return Real(( m_ / arg.m_ ) * factor_); }
// Умножение на целое число типа long int
Real operator*(const long &i) const { return Real(m_ * i); }
// Деление на целое число типа long int
Real operator/(const long &i) const { return Real(m_ / i); }
// Отношения
bool operator==(const Real &arg) const { return m_ == arg.m_; }
bool operator!=(const Real &arg) const { return m_ != arg.m_; }
bool operator>(const Real &arg) const { return m_ > arg.m_; }
bool operator>=(const Real &arg) const { return m_ >= arg.m_; }
bool operator<(const Real &arg) const { return m_ < arg.m_; }
bool operator<=(const Real &arg) const { return m_ <= arg.m_; }
// Оператор приведения к типу bool
explicit operator bool() {
return m_ != 0;
}
// Конвертирование в double
double toDouble() const {
return double(m_) / factor_;
}
// Дружественный оператор для вывода числа в выходной поток os (cout, ...)
friend std::ostream &operator<<(std::ostream &os, const Real &arg) {
return os << ( arg.toDouble() / double(arg.factor_) ) << '*' << 2 << '^' << E - 1;
}
};
int main() {
Real<10> a(1.3), b(1.2);
cout << "A: " << a << " (" << a.toDouble() << ")\n";
cout << "B: " << b << " (" << b.toDouble() << ")\n";
cout << "A + B: " << a + b << " (" << ( a + b ).toDouble() << ")\n";
cout << "A - B: " << a - b << " (" << ( a - b ).toDouble() << ")\n";
cout << "A * B: " << a * b << " (" << ( a * b ).toDouble() << ")\n";
cout << "A / B: " << a / b << " (" << ( a / b ).toDouble() << ")\n";
cout << "A * 2: " << a * 2 << " (" << ( a * 2 ).toDouble() << ")\n";
cout << "A / 2: " << a / 2 << " (" << ( a / 2 ).toDouble() << ")\n";
cout << "A == B: " << ( a == b ) << endl;
cout << "A != B: " << ( a != b ) << endl;
cout << "A > B: " << ( a > b ) << endl;
cout << "A >= B: " << ( a >= b ) << endl;
cout << "A < B: " << ( a < b ) << endl;
cout << "A <= B: " << ( a <= b ) << endl;
cout << "bool(0): " << bool(Real<10>(long(0))) << endl;
cout << "bool(5): " << bool(Real<10>(long(5))) << endl;
}
Соседние файлы в папке Решения лабораторных работ (местами есть ошибки)