C ++
 Computer >> コンピューター >  >> プログラミング >> C ++

C++の複素数


このセクションでは、C++で複素数を作成して使用する方法を説明します。 C ++で複素数クラスを作成できます。これは、複素数の実数部と虚数部をメンバー要素として保持できます。このクラスを処理するために使用されるいくつかのメンバー関数があります。

この例では、1つの複素数型クラス、つまり複素数を正しい形式で表示する関数を作成しています。 2つの複素数を加算および減算する2つの追加メソッドなど。

#include<iostream>
using namespace std;
class complex {
   int real, img;
   public:
      complex() {
         //default constructor to initialize complex number to 0+0i
         real = 0; img = 0;
      }
      complex(int r, int i) {
         //parameterized constructor to initialize complex number.
         real = r; img = i;
      }
      void set();
      void get();
      void display();
      friend complex add(complex, complex);
      friend complex sub(complex, complex);
};
void complex::set() {
   cout << "Enter Real part: ";
   cin >> real;
   cout << "Enter Imaginary Part: ";
   cin >> img;
}
void complex::get() {
   cout << "The complex number is: "<< real << "+" << img << "i" << endl;
}
void complex::display() {
   if(img < 0)
      if(img == -1)
         cout << "The complex number is: "<< real << "-i" << endl;
      else
         cout << "The complex number is: "<< real << img << "i" << endl;
      else
         if(img == 1)
            cout << "The complex number is: "<< real << " + i"<< endl;
         else
            cout << "The complex number is: "<< real << " + " << img << "i" <<
   endl;
}
complex add(complex c1, complex c2) {
   complex res;
   res.real = c1.real + c2.real;//addition for real part
   res.img = c1.img + c2.img;//addition for imaginary part
   return res;//the result after addition
}
complex sub(complex c1, complex c2) {
   complex res;
   res.real = c1.real - c2.real;//subtraction for real part
   res.img = c1.img - c2.img;//subtraction for imaginary part
   return res;//the result after subtraction
}
main() {
   complex n1(3, 2), n2(4, -3);
   complex result;
   result = add(n1,n2);
   result.display();
   result = sub(n1,n2);
   result.display();
}

出力

The complex number is: 7-i
The complex number is: -1 + 5i

  1. C++でのエマープ番号

    エマープ numberは特殊なタイプの数であり、その数字を逆にすると別の素数が作成されます(この素数は元の素数とは異なります)。 エマープは素数の逆です。 エマープではないいくつかの素数は、回文素数と1桁の素数です。 いくつかのエマープ番号 13、17、37、733です。 n未満のすべてのエマープ数を出力するプログラム。 ここでは、番号nが与えられており、すべてのemirp番号を出力する必要があります。 n以下。 問題を理解するために例を見てみましょう 入力: n =40 出力: 13、17、31、37 ソリューションアプローチ 指定された数よりも小さいすべてのエマー

  2. C++でのデュードニー番号

    与えられた数の底の数理論で定義された数は、最初の自然数の桁の合計が2番目の数の桁の合計に等しくなるように、別の自然数の完全な3乗に等しい自然数です。 (ウィキペディア)。 番号はヘンリー・デュードニーによって発見されました 。その数式 は- ここでは、整数nが与えられます。私たちの仕事は、与えられた番号nが人物番号であるかどうかを確認することです。 問題を理解するために例を見てみましょう 入力: N =17592 出力: いいえ 説明: 与えられた番号はダドニー番号ではありません。 ソリューションアプローチ- 解決策は、デュードニー番号の基本的な定義にあります。