C++程序:初始化和打印复数


复数是现代科学中一个非常基础的概念,最早在17世纪初被提出。复数的形式为 a + ib,其中 a 和 b 是实数。a 称为复数的实部,ib 称为复数的虚部。在 C++ 中,有一个类可以表示复数,即 complex 类。C++ 中的 complex 类可以表示和操作复数的各种运算。我们来看一下如何表示、初始化和显示复数。

使用类构造函数进行初始化

要使用 complex 类,我们必须导入 complex 库,可以使用 #include 语句导入或包含。下面描述了 complex 对象的声明和初始化。在第一个示例中,我们使用构造函数将值赋给复数的实部和虚部作为初始化。

语法

double value1 = <double value>;
double value2 = <double value>;
complex <double> cno(value1, value2);

算法

  • 将输入存储到两个数值变量中。

  • 将这两个变量传递给复数的构造函数。

  • 显示复数。

示例

#include <iostream>
#include <complex>
using namespace std;

//displays the complex number supplied
void display(complex <double> c){
   cout << "The complex number is: ";
   cout << real(c) << '+' << imag(c) << 'i' << endl;
}

//initializing the complex number
complex<double> solve( double real, double img ){
   complex<double> cno(real, img);
   return cno;
}
int main(){

   //the real and the imaginary values are represented as double values
   double v1 = 10;
   double v2 = 7;

   //creating and displaying the complex number
   display(solve(v1, v2));
   return 0;
}

输出

The complex number is: 10+7i

可以将任何数值数据类型用于复数变量的当前类型(double)代替。

使用赋值运算符进行初始化

我们也可以使用赋值运算符将实部和虚部赋值给复数。但是,要这样做,我们必须提供“a + ib”类型的数字,其中“a”和“b”都是数值。如果数字是整数,则会在小数点后添加零。编写实部“a”时必须使用小数点。例如,10 必须写成 10.0。

语法

//the real and imaginary parts have to be assigned as it is
complex <double> cno = 15.0 + 6i;

算法

  • 创建一个新的复数对象。

  • 使用“a + ib”表示法为对象赋值。

  • 显示复数值。

示例

#include <iostream>
#include <complex>
using namespace std;

//displays the complex number supplied
void display(complex <double> c){
   cout << "The complex number is: ";
   cout << real(c) << '+' << imag(c) << 'i' << endl;
}
int main(){
   
   //initializing a complex number object
   complex <double> cno = 15. + 6i;
   
   //displaying the complex number
   display(cno);
   return 0;
}

输出

The complex number is: 15+6i

显示复数

使用“real()”和“imag()”函数,分别显示复数的实部和虚部。“real()”函数显示复数的实部,“imag()”函数显示复数的虚部。这是一个示例。

语法

//displaying in the a + ib format
complex<double> c;
cout << real(c) << '+' << imag(c) << 'i' << endl;

算法

  • 创建一个新的复数对象。

  • 使用“a + ib”表示法为对象赋值。

  • 显示复数值。

示例

#include <iostream>
#include <complex>
using namespace std;
//displays the complex number supplied
void display(complex <double> c){
   cout << "The complex number is: ";
   cout << real(c) << '+' << imag(c) << 'i' << endl;
}
//initializing the complex number
complex<double> solve( double real, double img ){
   complex<double> cno(real, img);
   return cno;
}
int main(){
//the real and the imaginary values are represented as double values
   double v1 = 3;
   double v2 = 4;
//creating and displaying the complex number
   display(solve(v1, v2));
   return 0;
}

输出

The complex number is: 3+4i

结论

复数在广泛的科学领域中许多不同的程序中是必需的。C++ complex 类(包含在 header 中)提供了一个表示复数的接口。complex 类支持复数的所有运算,包括加法、减法、乘法、共轭、范数以及许多其他运算。正如我们在这篇文章中已经讨论过的,将常规数值转换为复数并不太难。我们需要注意的是,在显示复数时,必须注意数字的实部和虚部,否则可能会在程序中产生一些错误。

更新于:2022年12月7日

2K+ 次浏览

开启你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.