I need help with this program. It must use a header file (Complex.h) and Complex
ID: 3728645 • Letter: I
Question
I need help with this program. It must use a header file (Complex.h) and Complex.cpp.
The main.cpp is for part a is
#include <iostream>
using namespace std;
#include "Complex.h"
int main(void) {
double a, b;
const int MAX_ITERATIONS = 255;
cout << "Enter the coefficients of a complex number: ";
cin >> a;
cin >> b;
Complex c(a,b);
Complex r(0,0);
int i = 1;
while (true) {
r = r*r;
r = r+c;
//cout << i << " " << r << endl;
if (r.a*r.a + r.b*r.b > 4) break;
if (i == MAX_ITERATIONS) break;
i++;
}
cout << "Num iterations: " << i << endl;
cout << "Final value: " << r << endl;
}
Explanation / Answer
here is your files : --------->>>>>>
Complex.h : ------------->>>>>>>>
#ifndef _COMPLEX_H_
#define _COMPLEX_H_
#include<iostream>
#include<cmath>
using namespace std;
class Complex{
double real;
double image;
public:
Complex(double r,double i);
double length()const;
void setReal(double r);
void setImage(double i);
double getReal()const;
double getImage()const;
Complex& operator=(const Complex &oth);
Complex operator*(const Complex &oth);
Complex operator+(const Complex &oth);
friend ostream& operator<<(ostream &out,const Complex &oth);
};
#endif
Complex.cpp : ------->>>>>>>
#include "complex.h"
Complex::Complex(double r,double i){
real = r;
image = i;
}
void Complex::setImage(double i){
image = i;
}
void Complex::setReal(double r){
real = r;
}
double Complex::getImage()const{
return image;
}
double Complex::getReal()const{
return real;
}
double Complex::length()const{
return sqrt(real*real + image*image);
}
Complex& Complex::operator=(const Complex &oth){
real = oth.real;
image = oth.image;
return *this;
}
Complex Complex::operator*(const Complex &oth){
double r = (real*oth.real - image*oth.image);
double i = (real*oth.image + image*oth.real);
return Complex(r,i);
}
Complex Complex::operator+(const Complex &oth){
double r = real + oth.real;
double i = image + oth.image;
return Complex(r,i);
}
ostream& operator<<(ostream &out,const Complex &oth){
if(oth.getImage() >= 0){
out<<"("<<oth.getReal()<<" + "<<oth.getImage()<<"i)";
}else{
out<<"("<<oth.getReal()<<" - "<<oth.getImage()<<"i)";
}
return out;
}
main.cpp : ------------->>>>>>>>>>
#include <iostream>
using namespace std;
#include "Complex.h"
int main(void) {
double a, b;
const int MAX_ITERATIONS = 255;
cout << "Enter the coefficients of a complex number: ";
cin >> a;
cin >> b;
Complex c(a,b);
Complex r(0,0);
int i = 1;
while (true) {
r = r*r;
r = r+c;
//cout << i << " " << r << endl;
if (r.getReal()*r.getReal() + r.getImage()*r.getImage() > 4) break;
if (i == MAX_ITERATIONS) break;
i++;
}
cout << "Num iterations: " << i << endl;
cout << "Final value: " << r << endl;
}