java复数加减(java复数的加减)
华为云服务器特价优惠火热进行中! 2核2G2兆仅需 38 元;4核4G3兆仅需 79 元。购买时间越长越优惠!更多配置及优惠价格请咨询客服。
合作流程: |
本篇文章给大家谈谈java复数加减,以及java复数的加减对应的知识点,希望对各位有所帮助,不要忘了收藏本站喔。
微信号:cloud7591如需了解更多,欢迎添加客服微信咨询。
复制微信号
本文目录一览:
构建一个复数类,怎么用java实现复数的加减
public class ComplexDemo {
// main方法
public static void main(String[] a) {
Complex b = new Complex(2, 5);
Complex c = new Complex(3, -4);
System.out.println(b + "+" + c + "=" + b.add(c));
System.out.println(b + "-" + c + "=" + b.minus(c));
System.out.println(b + "*" + c + "=" + b.multiply(c));
System.out.println(b + "/" + c + "=" + b.divide(c));
}
}
// Complex类
class Complex {
private double m;// 实部
private double n;// 虚部
public Complex(double m, double n) {
this.m = m;
this.n = n;
}
// add
public Complex add(Complex c) {
return new Complex(m + c.m, n + c.n);
}
// minus
public Complex minus(Complex c) {
return new Complex(m - c.m, n - c.n);
}
// multiply
public Complex multiply(Complex c) {
return new Complex(m * c.m - n * c.n, m * c.n + n * c.m);
}
// divide
public Complex divide(Complex c) {
double d = Math.sqrt(c.m * c.m) + Math.sqrt(c.n * c.n);
return new Complex((m * c.m + n * c.n) / d, Math.round((m * c.n - n * c.m) / d));
}
public String toString() {
String rtr_str = "";
if (n 0)
rtr_str = "(" + m + "+" + n + "i" + ")";
if (n == 0)
rtr_str = "(" + m + ")";
if (n 0)
rtr_str = "(" + m + n + "i" + ")";
return rtr_str;
}
}
java中如何实现复数的加减?
不知道是不是 ~
//复数类。
public class Complex
{
private double real,im; //实部,虚部
public Complex(double real, double im) //构造方法
{
this.real = real;
this.im = im;
}
public Complex(double real) //构造方法重载
{
this(real,0);
}
public Complex()
{
this(0,0);
}
public Complex(Complex c) //拷贝构造方法
{
this(c.real,c.im);
}
public boolean equals(Complex c) //比较两个对象是否相等
{
return this.real==c.real this.im==c.im;
}
public String toString()
{
return "("+this.real+"+"+this.im+"i)";
}
public void add(Complex c) //两个对象相加
{ //改变当前对象,没有返回新对象
this.real += c.real;
this.im += c.im;
}
public Complex plus(Complex c) //两个对象相加,与add()方法参数一样不能重载
{ //返回新创建对象,没有改变当前对象
return new Complex(this.real+c.real, this.im+c.im);
}
public void subtract(Complex c) //两个对象相减
{ //改变当前对象,没有返回新对象
this.real -= c.real;
this.im -= c.im;
}
public Complex minus(Complex c) //两个对象相减,与subtract()方法参数一样不能重载
{ //返回新创建的对象,没有改变当前对象
return new Complex(this.real-c.real, this.im-c.im);
}
}
class Complex__ex
{
public static void main(String args[])
{
Complex a = new Complex(1,2);
Complex b = new Complex(3,5);
Complex c = a.plus(b); //返回新创建对象
System.out.println(a+" + "+b+" = "+c);
}
}
/*
程序运行结果如下:
(1.0+2.0i) + (3.0+5.0i) = (40.0+7.0i)
*/

java 编写一个可对复数进行加减运算的程序
1、real和image这两个field前面的static去掉。
2、public Complex() 这个构造器去掉,如果要接受输入的话,应该放到main方法里,这样这个类更清晰。
3、静态方法Complex_add和Complex_minus没指定返回值类型,应该返回的是Complex。另外方法名字首字母应小写。
4、参考这个:
关于java复数加减和java复数的加减的介绍到此就结束了,不知道你从中找到你需要的信息了吗 ?如果你还想了解更多这方面的信息,记得收藏关注本站。
