Untitled
By: a guest | Mar 19th, 2010 | Syntax:
C++ | Size: 1.98 KB | Hits: 54 | Expires: Never
#include <iostream>
#include <cmath>
using std::cout;
using std::cin;
using std::endl;
using std::fixed;
class Complex
{
protected:
float re, im;
public:
Complex(){
re = 0;
im = 0;
}
Complex(float re){
this->re = re;
this->im = 0;
}
Complex(float re, float im){
this->re = re;
this->im = im;
}
void print(){
cout << fixed << re;
if(im != 0)
if (im > 0)
cout << " + " << fixed << im << "i";
else
cout << " - " << fixed << -im << "i";
cout << endl;
}
void read(){
float a, b;
cin >> a >> b;
re = a;
im = b;
}
float mod(){
return re * re + im * im;
}
Complex operator+ (Complex &x){
return Complex(re + x.re, im + x.im);
}
Complex operator- (Complex &x){
return Complex(re - x.re, im - x.im);
}
Complex operator* (Complex &x){
return Complex(re * x.re - im * x.im, re * x.im + im * x.re);
}
Complex operator/ (Complex &x){
if(x.re == 0 && x.im ==0){
cout << "Divide by zero!";
return Complex(0, 0);
}
else
return Complex((re * x.re + im * x.im) / x.mod(),
(re * x.im - im * x.re) / x.mod());
}
};
int main(){
Complex x, y, z;
char action;
cout << "Enter first number: ";
x.read();
cout << "Enter second number: ";
y.read();
cout << "Choose action (+, -, *, /): ";
cin >> action;
switch(action){
case '+':
z = x + y;
break;
case '-':
z = x - y;
break;
case '*':
z = x * y;
break;
case '/':
z = x / y;
break;
}
cout << "Answer: ";
z.print();
float a, b, c;
Complex *x1, *x2;
cout << "Enter coefficients: ";
cin >> a >> b >> c;
float D = b * b - 4 * a * c;
if(D >= 0){
x1 = new Complex((- b + sqrt(D)) / (2 * a));
x2 = new Complex((- b - sqrt(D)) / (2 * a));
} else {
x1 = new Complex(-b / (2 * a), sqrt(-D) / (2 * a));
x2 = new Complex(-b / (2 * a), -(sqrt(-D) / (2 * a)));
}
cout << "x1 = ";
x1->print();
cout << "x2 = ";
x2->print();
return 0;
}