您的位置:首页 > 编程语言 > Java开发

Java课程设计 复数类 实现加、减、乘法

2011-08-23 11:47 375 查看
复数类:

// Filename: Complex.java

class Complex
{
private double real;
private double imag;

Complex()
{
//System.out.println("默认构造函数");
}

Complex(String r, String i)
{
//Double d1 = new Double(r);
//Double d2 = new Double(i);

real = Double.parseDouble(r);
imag = Double.parseDouble(i);

//System.out.println("String构造函数");
}

Complex(double r, double i)
{
real = r;
imag = i;

//System.out.println("double构造函数");
}

Complex add(Complex cc)
{
Complex tmp = new Complex(real + cc.real, imag + cc.imag);
return tmp;
}

Complex sub(Complex cc)
{
Complex tmp = new Complex(real - cc.real, imag - cc.imag);
return tmp;
}

Complex mul(Complex cc)
{
double R = 0.0, I = 0.0;
R = real * cc.real - imag * cc.imag;
I = real * cc.imag + imag * cc.real;
Complex tmp = new Complex(R, I);
return tmp;
}

void print()
{
System.out.println("( " + real + ", " + imag + " )");
}
}


测试程序:

// Filename: ComplexTestDrive

import java.io.*;
import java.util.*;
import java.lang.Double;

public class ComplexTestDrive
{
public static void main(String[] args)
{
int ch = 0;	//算术操作符: + - *

Scanner in = new Scanner(System.in);

String A, B;	//A是实部, B是虚部
//while(true)
//{
System.out.println("Input the first plural");
System.out.print("Input the real: ");
A = in.next();
System.out.print("Input the image: ");
B = in.next();

Complex c1 = new Complex(A, B);

System.out.println("Input the second plural");
System.out.print("Input the real: ");
A = in.next();
System.out.print("Input the image: ");
B = in.next();

Complex c2 = new Complex(A, B);

//c1.print();
//c2.print();

System.out.println("1. A + b");
System.out.println("2. A - B");
System.out.println("3. A * B");

System.out.print("Choose your operation: ");
try{
BufferedReader br = new BufferedReader( new InputStreamReader(System.in) );
ch = Integer.parseInt(br.readLine());
}catch(IOException ex){}
//System.out.println("ch = " + ch);

Complex c3 = new Complex();

switch(ch)
{
case 1:c3 = c1.add(c2);c3.print();break;
case 2:c3 = c1.sub(c2);c3.print();break;
case 3:c3 = c1.mul(c2);c3.print();break;
default:System.out.println("Choice Error!!");break;
}

//}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: