21xrx.com
2024-09-19 09:35:38 Thursday
登录
文章检索 我的文章 写文章
C++实现一元二次方程的复数根求解
2023-07-05 05:16:24 深夜i     --     --
C++ 一元二次方程 复数根 求解
// 复数不等

    return (real != other.real) || (imag != other.imag);

一元二次方程是一种常见的数学问题,在实际生活中也有广泛应用。如果方程的解是实数,求解是比较简单的。但如果方程的根是复数,则需要使用复数的运算方法进行求解。在C++语言中,我们可以通过定义复数类来实现一元二次方程的复数根求解。

首先,我们需要了解复数的概念。复数是由实部和虚部组成的数,通常表示为a+bi的形式,其中a为实部,b为虚部,i表示虚数单位(i²=-1)。在计算复数的加减乘除等运算时,我们需要按照实部和虚部分别进行运算。

接下来,我们来实现求解一元二次方程的复数根的代码。假设一元二次方程的标准形式为ax²+bx+c=0,其中a、b、c均为实数,我们可以使用下面的代码来求解该方程的复数根:


#include<iostream>

#include<cmath>

using namespace std;

class Complex { // 复数类

public:

  double real; // 实部

  double imag; // 虚部

  Complex(double r = 0, double i = 0) : real(r), imag(i) {}

  Complex operator+(const Complex& other) const { // 复数加法

    return Complex(real + other.real, imag + other.imag);

  }

  Complex operator-(const Complex& other) const { // 复数减法

    return Complex(real - other.real, imag - other.imag);

  }

  Complex operator*(const Complex& other) const { // 复数乘法

    return Complex(real * other.real - imag * other.imag, real * other.imag + imag * other.real);

  }

  Complex operator/(const Complex& other) const { // 复数除法

    double denom = other.real * other.real + other.imag * other.imag;

    return Complex((real * other.real + imag * other.imag) / denom, (imag * other.real - real * other.imag) / denom);

  }

  bool operator==(const Complex& other) const { // 复数相等

    return (real == other.real) && (imag == other.imag);

  }

  bool operator!=(const Complex& other) const { // 复数不等

    return (real != other.real) || (imag != other.imag);

  }

};

Complex sqrt_c(const Complex& c) { // 求解复数的平方根

  double r = sqrt(c.real * c.real + c.imag * c.imag);

  double theta = atan2(c.imag, c.real);

  return Complex(sqrt(r) * cos(theta / 2), sqrt(r) * sin(theta / 2));

}

void solve_complex_eq(double a, double b, double c) { // 求解一元二次方程的复数根

  Complex disc = Complex(b * b - 4 * a * c, 0);

  Complex x1 = (-b + sqrt_c(disc)) / (2 * a);

  Complex x2 = (-b - sqrt_c(disc)) / (2 * a);

  cout << "x1 = " << x1.real << " + " << x1.imag << "i, x2 = " << x2.real << " + " << x2.imag << "i" << endl;

}

int main() {

  double a, b, c;

  cout << "请输入一元二次方程的系数(ax²+bx+c=0):" << endl;

  cout << "a = ";

  cin >> a;

  cout << "b = ";

  cin >> b;

  cout << "c = ";

  cin >> c;

  solve_complex_eq(a, b, c);

  return 0;

}

在代码中,我们先定义了复数类Complex,包含了实部和虚部的定义,以及复数加减乘除等运算符的重载函数。接着,我们定义了一个求解复数平方根的函数sqrt_c,以及求解一元二次方程的复数根的函数solve_complex_eq。在主函数中,我们通过输入a、b、c求解方程的复数根,并输出结果。

总的来说,C++实现一元二次方程的复数根求解非常简单。通过定义一个复数类和相应的运算符重载函数,我们可以方便地进行复数加减乘除等运算,并实现一元二次方程的复数根的求解,从而解决实际问题。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复