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

复数类:

// 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;
			}
			
		//}
	}
}


  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值