您的位置:首页 > 其它

蓝桥杯 算法训练 复数运算

2016-04-29 12:45 465 查看
  编程实现两个复数的运算。设有两个复数 和 ,则他们的运算公式为:

  要求:(1)定义一个结构体类型来描述复数。

  (2)复数之间的加法、减法、乘法和除法分别用不用的函数来实现。

  (3)必须使用结构体指针的方法把函数的计算结果返回。

  说明:用户输入:运算符号(+,-,*,/) a b c d.

  输出:a+bi,输出时不管a,b是小于0或等于0都按该格式输出,输出时a,b都保留两位。

输入:

  - 2.5 3.6 1.5 4.9

输出:

  1.00+-1.30i

package com.ALGO;

import java.text.DecimalFormat;
import java.util.Scanner;

public class _142{
public static class FuShu{
public FuShu(double a, double b) {
// TODO Auto-generated constructor stub
this.a = a;
this.b = b;
}
public double a;
public double b;
public String toString() {
DecimalFormat format = new DecimalFormat("0.00");
return format.format(a)+"+"+format.format(b)+"i";
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner (System.in);
String operator = scan.next();
char op = operator.charAt(0);
double a = scan.nextDouble();
double b = scan.nextDouble();
double c = scan.nextDouble();
double d = scan.nextDouble();
FuShu one = new FuShu(a,b);
FuShu two = new FuShu(c,d);
FuShu three = null;
switch(op){
case '+':three = add(one, two);break;
case '-':three = sub(one, two);break;
case '*':three = mul(one, two);break;
case '/':three = div(one, two);break;
}
System.out.println(three.toString());

}
private static FuShu div(FuShu one, FuShu two) {
FuShu temp = new FuShu((one.a*two.a+one.b*two.b)/(two.b*two.b+two.a*two.a), (one.b*two.a+one.a*two.b)/(two.b*two.b+two.a*two.a));
return temp;
}

private static FuShu mul(FuShu one, FuShu two) {
FuShu temp = new FuShu(one.a*two.a-one.b*two.b, one.a*two.b+one.b*two.a);
return temp;
}

private static FuShu sub(FuShu one, FuShu two) {
FuShu temp = new FuShu(one.a-two.a, one.b-two.b);
return temp;
}

private static FuShu add(FuShu one, FuShu two) {
FuShu temp = new FuShu(one.a+two.a, one.b+two.b);
return temp;
}

}


此处测试100分,有需要的同志就参考可以

另外楼主留下新浪博客-@雷锹。有兴趣的通知可以粉我一直交流
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: