C++的问题:定义描述复数的结构体类型变量,并实现复数之间的加减法运算和输入输出
#include "stdafx.h"
#include <iostream>
using namespace std;
struct complex //定义一个复数结构体
{
int real; //实数,数据类型根据自己的要求改吧
int imaginary; //虚数,同上
friend complex operator + (complex a, complex b);
//重载运算符“+”,其运算结果为复数,即返回类型为complex
friend complex operator - (complex a, complex b);
//同上
friend ostream & operator << (ostream &out, complex a);
//重载操作符<<,这里用到输出流ostream
void setnumber(int a, int b)
//用于输入的函数,这里重载>>的话会很麻烦,
//你可以自己尝试一下输入an+bi并读取,并没有依次输入系数简单
{
real = a;
imaginary = b;
}
};
complex operator + (complex a, complex b)
{
int x = a.real + b.real; //复数加法:实数加实数
int y = a.imaginary + b.imaginary;//虚数加虚数
complex temp; //声明一个复数temp
temp.setnumber(x, y); //将计算的结果赋给temp
return temp; //并返回
}
complex operator - (complex a, complex b)//同上
{
int x = a.real - b.real;
int y = a.imaginary - b.imaginary;
complex temp;
temp.setnumber(x, y);
return temp;
}
ostream & operator << (ostream &out, complex a)
//这里我分类讨论了一下,为了省略0产生的赘余
{
if (a.real == 0)
return out << a.imaginary << "i";
else if (a.imaginary==0)
return out << a.real;
else
return out << a.real << "+" << a.imaginary << "i";
}
//乘除法的话根据这个自己套公式吧
void main()
//主函数根据要求自己写吧
{
complex a;
complex b;
cout << "请分别输入第一个数的实数和虚数部分" << endl;
int ar, ai;
cin >> ar >> ai;
a.setnumber(ar, ai);
cout << "请输入另一个数的实数和虚数部分" << endl;
int br, bi;
cin >> br >> bi;
b.setnumber(br,bi);
cout << "a+b=" << a + b << endl;
cout << "a-b=" << a - b << endl;
//输入部分可以用for循环和数组来满足多个复数的声明和赋值
}
2023-08-15 广告