vs2017\vs2019 构造复数类实现加减乘除四则运算
这是针对于博客vs2017安装和使用教程(详细)和vs2019安装和使用教程(详细)的构造复数类实现加减乘除四则运算的新建示例
目录
一、项目结构
1.头文件
- Complex.h
2.源文件
- Complex.cpp
- main.cpp
二、代码
1.Complex.h
-
#pragma once
-
-
class Complex {
-
double real;//实部
-
double imag;//虚部
-
public:
-
Complex(double r, double i);//构造函数
-
//Complex operator+(Complex &c);//加法
-
//Complex operator-(Complex &c);//减法
-
//Complex operator*(Complex &c);//乘法
-
//Complex operator/(Complex &c);//除法
-
Complex *Compute(Complex &c,char op);
-
double GetReal();
-
double GetImag();
-
void display();
-
};
2.Complex.cpp
-
#include<math.h>
-
#include"Complex.h"
-
#include<iostream>
-
using namespace std;
-
Complex::Complex(double r0, double i0) {
-
real = r0;
-
imag = i0;
-
}
-
-
double Complex::GetReal() {
-
return real;
-
}
-
-
double Complex::GetImag() {
-
return imag;
-
}
-
-
Complex *Complex::Compute(Complex &c, char op) {
-
double r1, i1, temp;//防止重定义
-
Complex *q;
-
switch (op)
-
{
-
case '+':
-
r1 = real + c.real;//实部相加
-
i1 = imag + c.imag;//虚部相加
-
q = new Complex(r1, i1);
-
return q;
-
break;
-
case '-':
-
r1 = real - c.real;//实部相减
-
i1 = imag - c.imag;//虚部相减
-
q =new Complex(r1, i1);
-
return q;
-
break;
-
case '*':
-
r1 = real * c.real - imag * c.imag;//实部
-
i1 = imag * c.real + real * c.imag;//虚部
-
q =new Complex(r1, i1);
-
return q;
-
break;
-
case '/':
-
temp = c.real*c.real + c.imag*c.imag;//分母
-
r1 = (real * c.real + imag * c.imag) / temp;//实部
-
i1 = (imag * c.real - real * c.imag) / temp;//虚部
-
q =new Complex(r1, i1);
-
return q;
-
break;
-
default:
-
break;
-
}
-
}
-
-
void Complex::display() {
-
if (imag >= 0) {//虚部小于0,不应该出现+-
-
cout << "(" << real << "+" << imag << "i)";
-
}
-
else
-
{
-
cout << "(" << real << imag << "i)";
-
}
-
}
3.main.cpp
-
#include<iostream>
-
using namespace std;
-
#include"Complex.h"
-
-
int main() {
-
//Complex c1(1.0, 2.0);//测试构造函数
-
//Complex c2(3.0, 4.0);
-
//定义实部和虚部
-
double r1;
-
double i1;
-
double r2;
-
double i2;
-
-
cout << "请输入两个复数的实部和虚部:" << endl;
-
cin >> r1 >> i1 >> r2 >> i2;
-
-
char op;//运算符
-
cout << "请输入运算符:" << endl;
-
cin >> op;
-
-
Complex c1(r1, i1);
-
Complex c2(r2, i2);
-
-
//计算
-
Complex *q = c1.Compute(c2, op);
-
-
//输出结果
-
cout << "计算结果为:" << endl;
-
c1.display();
-
cout << " " << op << " ";
-
c2.display();
-
cout << "= ";
-
q->display();
-
getchar();
-
getchar();
-
return 0;
-
}
三、运行程序
1.点击“本地Windows调试器”
2.我们以除法为例,计算(1+2i) / (3+4i)的结果,如下输入
3.输入运算符“/”
4.运行结果
5.负数的例子同理,计算(1-2i) / (3+4i)直接给出结果
四、注意事项
1.注意display()函数,作用是虚部小于0,不允许出现+-,即加一个负数
2.注意自己写的头文件用双引号""括起来而不是<>
3.Compute()函数返回值为Complex指针
返回至原博客:
文章来源: nickhuang1996.blog.csdn.net,作者:悲恋花丶无心之人,版权归原作者所有,如需转载,请联系作者。
原文链接:nickhuang1996.blog.csdn.net/article/details/87879977
- 点赞
- 收藏
- 关注作者
评论(0)