Ybadoo - Soluções em Software Livre
Tutoriais
Programação Orientada a Objetos

(Deitel, 2003) Desenvolva uma classe chamada Complex para realizar aritmética com números complexos. Os números complexos têm a forma realPart + imaginaryPart * i, onde i é √-1. Utilize variáveis de ponto flutuante para representar os dados private da classe. Forneça um método construtor que permita que um objeto dessa classe seja inicializado quando ele for declarado. Forneça um construtor sem argumentos com valores default caso nenhum inicializador seja fornecido. Forneça métodos public para cada um dos itens a seguir:

  1. somar dois números Complex, as partes reais são somadas de um lado e as partes imaginárias são somadas de outro;
  2. subtrair dois números Complex, a parte real do operando direito é subtraída da parte real do operando esquerdo e a parte imaginária do operando direito é subtraída da parte imaginária do operando esquerdo;
  3. imprimir os números Complex na forma (a, b), onde a é a parte real e b é a parte imaginária.

 

Terminal

ybadoo@server:~$ ./application
Implementação na Linguagem de Programação Java Implementação na Linguagem de Programação C++
Diagrama de Classes na Linguagem de Programação Java Complex.java Application.java
Diagrama de Classes
Diagrama de Classes na Linguagem de Programação Java

Arquivo Complex.java

/*************************************************************************
 * Copyright (C) 2009/2024 - Cristiano Lehrer (cristiano@ybadoo.com.br)  *
 *                  Ybadoo - Solucoes em Software Livre (ybadoo.com.br)  *
 *                                                                       *
 * Permission is granted to copy, distribute and/or modify this document *
 * under the terms of the GNU Free Documentation License, Version 1.3 or *
 * any later version published by the  Free Software Foundation; with no *
 * Invariant Sections,  no Front-Cover Texts, and no Back-Cover Texts. A *
 * A copy of the  license is included in  the section entitled "GNU Free *
 * Documentation License".                                               *
 *                                                                       *
 * Ubuntu 16.10 (GNU/Linux 4.8.0-39-generic)                             *
 * OpenJDK Version "1.8.0_121"                                           *
 * OpenJDK 64-Bit Server VM (build 25.121-b13, mixed mode)               *
 *************************************************************************/

package com.ybadoo.tutoriais.poo.tutorial02.exercicio30;

/**
 * Classe responsavel pela representacao de um numero complexo
 */
public class Complex
{
  /**
   * Parte real do numero complexo
   */
  private double realPart;

  /**
   * Parte imaginaria do numero complexo
   */
  private double imaginaryPart;

  /**
   * Construtor para inicializar o numero complexo
   */
  public Complex()
  {
    this(0.0, 0.0);
  }

  /**
   * Construtor para inicializar a parte real e a parte imaginaria
   * do numero complexo
   *
   * @param realPart parte real do numero complexo
   * @param imaginaryPart parte imaginaria do numero complexo
   */
  public Complex(double realPart, double imaginaryPart)
  {
    this.realPart = realPart;

    this.imaginaryPart = imaginaryPart;
  }

  /**
   * Retornar a parte real do numero complexo
   *
   * @return parte real do numero complexo
   */
  public double getRealPart()
  {
    return realPart;
  }

  /**
   * Retornar a parte imaginaria do numero complexo
   *
   * @return parte imaginaria do numero complexo
   */
  public double getImaginaryPart()
  {
    return imaginaryPart;
  }

  /**
   * Retornar um novo objeto Complex cujo valor eh this + other
   *
   * @param other numero complexo a ser adicionado
   * @return novo objeto Complex cujo valor eh this + other
   */
  public Complex addition(Complex other)
  {
    double real = realPart + other.realPart;

    double imaginary = imaginaryPart + other.imaginaryPart;

    return new Complex(real, imaginary);
  }

  /**
   * Retornar um novo objeto Complex cujo valor eh this - other
   *
   * @param other numero complexo a ser subtraido
   * @return novo objeto Complex cujo valor eh this - other
   */
  public Complex subtraction(Complex other)
  {
    double real = realPart - other.realPart;

    double imaginary = imaginaryPart - other.imaginaryPart;

    return new Complex(real, imaginary);
  }

  /* (non-Javadoc)
   * @see java.lang.Object#toString()
   */
  @Override
  public String toString()
  {
    return "(" + realPart + ", " + imaginaryPart + ")";
  }
}

Arquivo Application.java

/*************************************************************************
 * Copyright (C) 2009/2024 - Cristiano Lehrer (cristiano@ybadoo.com.br)  *
 *                  Ybadoo - Solucoes em Software Livre (ybadoo.com.br)  *
 *                                                                       *
 * Permission is granted to copy, distribute and/or modify this document *
 * under the terms of the GNU Free Documentation License, Version 1.3 or *
 * any later version published by the  Free Software Foundation; with no *
 * Invariant Sections,  no Front-Cover Texts, and no Back-Cover Texts. A *
 * A copy of the  license is included in  the section entitled "GNU Free *
 * Documentation License".                                               *
 *                                                                       *
 * Ubuntu 16.10 (GNU/Linux 4.8.0-39-generic)                             *
 * OpenJDK Version "1.8.0_121"                                           *
 * OpenJDK 64-Bit Server VM (build 25.121-b13, mixed mode)               *
 *************************************************************************/

package com.ybadoo.tutoriais.poo.tutorial02.exercicio30;

import java.util.Scanner;

/**
 * Classe responsavel pela execucao da classe Complex
 */
public class Application
{
  /**
   * Construtor para inicializar a execucao da classe Complex
   */
  private Application()
  {

  }

  /**
   * Metodo principal da linguagem de programacao Java
   *
   * @param args argumentos da linha de comando (nao utilizado)
   */
  public static void main(String[] args)
  {
    Scanner scanner = new Scanner(System.in);

    System.out.println("Forneça o primeiro número complexo");

    System.out.print("Valor da parte real: ");

    double realPart = scanner.nextDouble();

    System.out.print("Valor da parte imaginária: ");

    double imaginaryPart = scanner.nextDouble();

    Complex complex1 = new Complex(realPart, imaginaryPart);

    System.out.println("Forneça o segundo número complexo");

    System.out.print("Valor da parte real: ");

    realPart = scanner.nextDouble();

    System.out.print("Valor da parte imaginária: ");

    imaginaryPart = scanner.nextDouble();

    Complex complex2 = new Complex(realPart, imaginaryPart);

    scanner.close();

    Complex complex3 = complex1.addition(complex2);

    Complex complex4 = complex1.subtraction(complex2);

    System.out.println(complex1 + " + " + complex2 + " = " + complex3);

    System.out.println(complex1 + " - " + complex2 + " = " + complex4);
  }
}
Diagrama de Classes na Linguagem de Programação C++ Complex.hpp Complex.cpp Application.cpp makefile
Diagrama de Classes
Diagrama de Classes na Linguagem de Programação C++

Arquivo Complex.hpp

/*************************************************************************
 * Copyright (C) 2009/2024 - Cristiano Lehrer (cristiano@ybadoo.com.br)  *
 *                  Ybadoo - Solucoes em Software Livre (ybadoo.com.br)  *
 *                                                                       *
 * Permission is granted to copy, distribute and/or modify this document *
 * under the terms of the GNU Free Documentation License, Version 1.3 or *
 * any later version published by the  Free Software Foundation; with no *
 * Invariant Sections,  no Front-Cover Texts, and no Back-Cover Texts. A *
 * A copy of the  license is included in  the section entitled "GNU Free *
 * Documentation License".                                               *
 *                                                                       *
 * Ubuntu 16.10 (GNU/Linux 4.8.0-39-generic)                             *
 * g++ (Ubuntu 6.2.0-5ubuntu12) 6.2.0 20161005                           *
 *************************************************************************/

#ifndef COMPLEX_HPP
#define COMPLEX_HPP

#include <string>

/**
 * Classe responsavel pela representacao de um numero complexo
 */
class Complex
{
  public:

  /**
   * Construtor para inicializar o numero complexo
   */
  Complex();

  /**
   * Construtor para inicializar a parte real e a parte imaginaria
   * do numero complexo
   *
   * @param realPart parte real do numero complexo
   * @param imaginaryPart parte imaginaria do numero complexo
   */
  Complex(const double realPart, const double imaginaryPart);

  /**
   * Retornar a parte real do numero complexo
   *
   * @return parte real do numero complexo
   */
  double getRealPart() const;

  /**
   * Retornar a parte imaginaria do numero complexo
   *
   * @return parte imaginaria do numero complexo
   */
  double getImaginaryPart() const;

  /**
   * Retornar um novo objeto Complex cujo valor eh this + other
   *
   * @param other numero complexo a ser adicionado
   * @return novo objeto Complex cujo valor eh this + other
   */
  Complex* addition(const Complex* other) const;

  /**
   * Retornar um novo objeto Complex cujo valor eh this - other
   *
   * @param other numero complexo a ser subtraido
   * @return novo objeto Complex cujo valor eh this - other
   */
  Complex* subtraction(const Complex* other) const;

  /*
   * Retornar o objeto Complex como um texto na forma (a, b)
   *
   * @return objeto Complex como um texto na forma (a, b)
   */
  std::string toString() const;

  private:

  /**
   * Parte real do numero complexo
   */
  double realPart;

  /**
   * Parte imaginaria do numero complexo
   */
  double imaginaryPart;
};

#endif

Arquivo Complex.cpp

/*************************************************************************
 * Copyright (C) 2009/2024 - Cristiano Lehrer (cristiano@ybadoo.com.br)  *
 *                  Ybadoo - Solucoes em Software Livre (ybadoo.com.br)  *
 *                                                                       *
 * Permission is granted to copy, distribute and/or modify this document *
 * under the terms of the GNU Free Documentation License, Version 1.3 or *
 * any later version published by the  Free Software Foundation; with no *
 * Invariant Sections,  no Front-Cover Texts, and no Back-Cover Texts. A *
 * A copy of the  license is included in  the section entitled "GNU Free *
 * Documentation License".                                               *
 *                                                                       *
 * Ubuntu 16.10 (GNU/Linux 4.8.0-39-generic)                             *
 * g++ (Ubuntu 6.2.0-5ubuntu12) 6.2.0 20161005                           *
 *************************************************************************/

#include <sstream>

#include "Complex.hpp"

/**
 * Construtor para inicializar o numero complexo
 */
Complex::Complex()
{
  Complex::realPart = 0.0;

  Complex::imaginaryPart = 0.0;
}

/**
 * Construtor para inicializar a parte real e a parte imaginaria
 * do numero complexo
 *
 * @param realPart parte real do numero complexo
 * @param imaginaryPart parte imaginaria do numero complexo
 */
Complex::Complex(const double realPart, const double imaginaryPart)
{
  Complex::realPart = realPart;

  Complex::imaginaryPart = imaginaryPart;
}

/**
 * Retornar a parte real do numero complexo
 *
 * @return parte real do numero complexo
 */
double Complex::getRealPart() const
{
  return realPart;
}

/**
 * Retornar a parte imaginaria do numero complexo
 *
 * @return parte imaginaria do numero complexo
 */
double Complex::getImaginaryPart() const
{
  return imaginaryPart;
}

/**
 * Retornar um novo objeto Complex cujo valor eh this + other
 *
 * @param other numero complexo a ser adicionado
 * @return novo objeto Complex cujo valor eh this + other
 */
Complex* Complex::addition(const Complex* other) const
{
  double realPart = Complex::realPart + other->getRealPart();

  double imaginaryPart = Complex::imaginaryPart + other->imaginaryPart;

  return new Complex(realPart, imaginaryPart);
}

/**
 * Retornar um novo objeto Complex cujo valor eh this - other
 *
 * @param other numero complexo a ser subtraido
 * @return novo objeto Complex cujo valor eh this - other
 */
Complex* Complex::subtraction(const Complex* other) const
{
  double realPart = Complex::realPart - other->getRealPart();

  double imaginaryPart = Complex::imaginaryPart - other->imaginaryPart;

  return new Complex(realPart, imaginaryPart);
}

/*
 * Retornar o objeto Complex como um texto na forma (a, b)
 *
 * @return objeto Complex como um texto na forma (a, b)
 */
std::string Complex::toString() const
{
  std::stringstream buffer;

  buffer << "(" << realPart << ", " << imaginaryPart << ")";

  return buffer.str();
}

Arquivo Application.cpp

/*************************************************************************
 * Copyright (C) 2009/2024 - Cristiano Lehrer (cristiano@ybadoo.com.br)  *
 *                  Ybadoo - Solucoes em Software Livre (ybadoo.com.br)  *
 *                                                                       *
 * Permission is granted to copy, distribute and/or modify this document *
 * under the terms of the GNU Free Documentation License, Version 1.3 or *
 * any later version published by the  Free Software Foundation; with no *
 * Invariant Sections,  no Front-Cover Texts, and no Back-Cover Texts. A *
 * A copy of the  license is included in  the section entitled "GNU Free *
 * Documentation License".                                               *
 *                                                                       *
 * Ubuntu 16.10 (GNU/Linux 4.8.0-39-generic)                             *
 * g++ (Ubuntu 6.2.0-5ubuntu12) 6.2.0 20161005                           *
 *************************************************************************/

#include <iostream>

#include "Complex.hpp"

/**
 * Metodo principal da linguagem de programacao C++
 *
 * @param argc quantidade de argumentos na linha de comando (nao utilizado)
 * @param argv argumentos da linha de comando (nao utilizado)
 */
int main(int argc, char** argv)
{
  using namespace std;

  double realPart;

  double imaginaryPart;

  cout << "Forneça o primeiro número complexo" << endl;

  cout << "Valor da parte real: ";
  cin  >> realPart;

  cout << "Valor da parte imaginária: ";
  cin  >> imaginaryPart;

  Complex* complex1 = new Complex(realPart, imaginaryPart);

  cout << "Forneça o segundo número complexo" << endl;

  cout << "Valor da parte real: ";
  cin  >> realPart;

  cout << "Valor da parte imaginária: ";
  cin  >> imaginaryPart;

  Complex* complex2 = new Complex(realPart, imaginaryPart);

  Complex* complex3 = complex1->addition(complex2);

  Complex* complex4 = complex1->subtraction(complex2);

  cout << complex1->toString() << " + " << complex2->toString()
       << " = " << complex3->toString() << endl;

  cout << complex1->toString() << " - " << complex2->toString()
       << " = " << complex4->toString() << endl;

  delete complex1;

  delete complex2;

  delete complex3;

  delete complex4;

  return 0;
}

Arquivo makefile

##########################################################################
 # Copyright (C) 2009/2024 - Cristiano Lehrer (cristiano@ybadoo.com.br)  #
 #                  Ybadoo - Solucoes em Software Livre (ybadoo.com.br)  #
 #                                                                       #
 # Permission is granted to copy, distribute and/or modify this document #
 # under the terms of the GNU Free Documentation License, Version 1.3 or #
 # any later version published by the  Free Software Foundation; with no #
 # Invariant Sections,  no Front-Cover Texts, and no Back-Cover Texts. A #
 # A copy of the  license is included in  the section entitled "GNU Free #
 # Documentation License".                                               #
 #                                                                       #
 # Ubuntu 16.10 (GNU/Linux 4.8.0-39-generic)                             #
 # gcc/g++ (Ubuntu 6.2.0-5ubuntu12) 6.2.0 20161005                       #
 ##########################################################################

g++ -o Complex.o -c Complex.cpp

g++ -o Application.o -c Application.cpp

g++ -o application Complex.o Application.o

Deitel, H. M. (2003). Java, como programar. 4ª edição. Porto Alegre: Bookman. 1.386 páginas.