Odpowiedź :
Mam nadzieje, że o takie coś chodziło. Nie do końca rozumiem co ma się dziać przy mnożeniu i dzieleniu tych interwałów. Jeżeli doprecyzujesz to chętnie poprawię.
Kod:
#include <algorithm>
#include <iostream>
using namespace std;
class interval {
public:
interval() { m_left = m_right = 0; }
interval(double a_left, double a_right) {
m_left = a_left;
m_right = a_right;
}
double getLeft() { return m_left; }
double getRight() { return m_right; }
double getMiddle() { return (m_right - m_left) / 2; }
double getLength() { return m_right - m_left; }
interval operator-() { return interval(-m_left, -m_right); }
interval operator-(const interval &a_interval) {
return interval(m_left - a_interval.m_left, m_right - a_interval.m_right);
};
interval operator+(const interval &a_interval) {
return interval(m_left + a_interval.m_left, m_right + a_interval.m_right);
}
interval operator*(const double &a_value) {
return interval(m_left * a_value, m_right * a_value);
}
interval operator*(const interval &a_interval) {
//[a,b]*[c,d] = [min(a*c,a*d,b*c,b*d),max(...] ???
// Nie za bardzo wiem o co chodzi z tym "min i max" wiec wypisuje
// najmniejszy i największy element. Rozpisane na zmienne aby łatwiej było
// odczytać
const double ac = m_left * a_interval.m_left; // a*c
const double ad = m_left * a_interval.m_right; // a*d
const double bc = m_right * a_interval.m_left; // b*c
const double bd = m_right * a_interval.m_right; // b*d
const double left = min(ac, min(ad, min(bc, bd)));
const double right = max(ac, max(ad, max(bc, bd)));
return interval(left, right);
}
interval operator/(const interval &a_interval) {
// to samo co przy mnożeniu
const double ac = m_left / a_interval.m_left; // a*c
const double ad = m_left / a_interval.m_right; // a*d
const double bc = m_right / a_interval.m_left; // b*c
const double bd = m_right / a_interval.m_right; // b*d
const double left = min(ac, min(ad, min(bc, bd)));
const double right = max(ac, max(ad, max(bc, bd)));
return interval(left, right);
}
friend ostream &operator<<(ostream &os, const interval &a_interval) {
return os << '[' << a_interval.m_left << ',' << a_interval.m_right << ']';
}
private:
double m_left;
double m_right;
};
int main() {
interval a{1.0, 2.0};
interval b{4.0, 8.0};
cout << "a = " << a << endl;
cout << "b = " << 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 left = " << a.getLeft() << endl;
cout << "a right = " << a.getRight() << endl;
cout << "a middle = " << a.getMiddle() << endl;
cout << "a length = " << a.getLength() << endl;
cout << "-a =" << -a << endl;
return 0;
}
Przykładowy wynik:
a = [1,2]
b = [4,8]
a + b = [5,10]
a - b = [-3,-6]
a * b = [4,16]
a / b = [0.125,0.5]
a left = 1
a right = 2
a middle = 0.5
a length = 1
-a =[-1,-2]