21xrx.com
2025-03-24 03:30:40 Monday
文章检索 我的文章 写文章
C++复数计算器源代码
2023-06-23 08:04:59 深夜i     19     0
C++ 复数 计算器 源代码 实现

C++是一种被广泛应用于计算机科学领域的编程语言,今天我们将要分享的是C++复数计算器源代码。这个计算器可以帮助我们解决一些复杂的数学问题,尤其是那些和复数有关的问题。

在开始之前,我们需要先了解什么是复数。复数可以写成a+bi的形式,其中a和b都是实数,i是虚数单位。复数的加、减、乘、除运算和实数运算类似,但有一些规则需要遵守,比如虚部乘以虚部为负数,以及除法时需要分子分母都乘以复数的共轭。了解了这些基础知识,我们就可以开始写代码了。

以下是C++复数计算器源代码的主要部分:

#include <iostream>
#include <string>
#include <sstream>
#include <cmath>
using namespace std;
class Complex {
private:
  double real;
  double imag;
public:
  Complex(double real = 0, double imag = 0)
    this->real = real;
    this->imag = imag;
  
  Complex operator+(const Complex &c2) const {
    return Complex(real + c2.real, imag + c2.imag);
  }
  Complex operator-(const Complex &c2) const {
    return Complex(real - c2.real, imag - c2.imag);
  }
  Complex operator*(const Complex &c2) const {
    return Complex(real * c2.real - imag * c2.imag, real * c2.imag + imag * c2.real);
  }
  Complex operator/(const Complex &c2) const {
    double denominator = c2.real * c2.real + c2.imag * c2.imag;
    return Complex((real * c2.real + imag * c2.imag) / denominator,
            (imag * c2.real - real * c2.imag) / denominator);
  }
  friend ostream &operator<<(ostream &os, const Complex &c) {
    os << c.real << (c.imag >= 0 ? "+" : "-") << abs(c.imag) << "i";
    return os;
  }
  friend istream &operator>>(istream &is, Complex &c) {
    string str;
    is >> str;
    int pos = str.find("+", 1);
    if (pos != string::npos) {
      string realStr = str.substr(0, pos);
      string imagStr = str.substr(pos + 1, str.length() - pos - 2);
      stringstream ss;
      ss << realStr << " " << imagStr;
      ss >> c.real >> c.imag;
    } else {
      pos = str.find("-", 1);
      string realStr = str.substr(0, pos);
      string imagStr = str.substr(pos + 1, str.length() - pos - 2);
      stringstream ss;
      ss << realStr << " " << "-" << imagStr;
      ss >> c.real >> c.imag;
    }
    return is;
  }
};
int main() {
  Complex c1, c2;
  cout << "请输入第一个复数:";
  cin >> c1;
  cout << "请输入第二个复数:";
  cin >> c2;
  cout << c1 << " + " << c2 << " = " << c1 + c2 << endl;
  cout << c1 << " - " << c2 << " = " << c1 - c2 << endl;
  cout << c1 << " * " << c2 << " = " << c1 * c2 << endl;
  cout << c1 << " / " << c2 << " = " << c1 / c2 << endl;
  return 0;
}

这个代码定义了一个名为Complex的类,其中存储了实部和虚部。四个成员函数分别实现了加、减、乘、除运算,以及两个友元函数实现了输入和输出。在main函数中,我们可以通过输入来得到两个复数的值,然后输出它们的加、减、乘、除结果。

运行这个程序,我们可以得到下面的输出结果(假设输入的两个复数分别为1+i和2-3i):

请输入第一个复数:1+i
请输入第二个复数:2-3i
1.000000+1.000000i + 2.000000-3.000000i = 3.000000-2.000000i
1.000000+1.000000i - 2.000000+3.000000i = -1.000000-2.000000i
1.000000+1.000000i * 2.000000-3.000000i = 5.000000-1.000000i
1.000000+1.000000i / 2.000000-3.000000i = -0.428571+0.285714i

我们可以看到,输出结果正确。这个复数计算器可以帮助我们解决很多复杂的数学问题,我们也可以根据需要对代码进行扩展,比如添加取模运算等等。希望这个代码能对大家有所帮助。

  
  

评论区