改编自https://www.cnblogs.com/youdiankun/p/4349681.html
1.实数的四则运算
import java.util.Scanner;
/*
* Java实现实数四则运算:
* 输入格式:
* 2
* +
* 3
*
* 输出格式:
* 5*/
public class Main {
static boolean flag;
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan=new Scanner(System.in);
double a=scan.nextDouble();
String str=scan.next();
double b=scan.nextDouble();
scan.close();
print(a,b,str);
System.out.println();
}
public static void print(double a,double b,String str) {
double c=0;
if(str.equals("+")) {
c=a+b;
}else if(str.equals("-")) {
c=a-b;
}else if(str.equals("*")) {
c=a*b;
}else if(str.equals("/")) {
if(b!=0) {
c=a/b;
}else {
System.out.println("error");
flag=true;
}
}
if(!flag) {
if(c-(Math.round(c))==0) {
System.out.print(Math.round(c));
}else {
System.out.print(c);
}
}
}
}
2.复数的四则运算
import java.util.Scanner;
/*
*Java实现两个复数的四则运算
*设计复数库,实现基本的复数加减乘除运算。
*输入时只需分别键入实部和虚部,以空格分割,两个复数之间用运算符分隔;
*输出时按a+bi的格式在屏幕上打印结果。参加样例输入和样例输出。
*注意考虑特殊情况,无法计算时输出字符串"error"。
*/
public class Main {
static boolean flag=true;
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan=new Scanner(System.in);
double a1=scan.nextDouble();
double b1=scan.nextDouble();
String str=scan.next();
double a2=scan.nextDouble();
double b2=scan.nextDouble();
scan.close();
double a=0;
double b=0;
//运算部分
if(str.equals("+")) {
a=a1+a2;
b=b1+b2;
}else if(str.equals("-")) {
a=a1-a2;
b=b1-b2;
}else if(str.equals("*")) {
a=a1*a2-b1*b2;
b=a1*b2+b1*a2;
}else if(str.equals("/")) {
if(a2==0&&b2==0) {
System.out.println("error");
flag=false;
}else {
//除法运算要用double类型
double c=a2*a2+b2*b2;
a=(a1*a2+b1*b2)/c;
b=(b1*a2-a1*b2)/c;
}
}
if(flag) {
print(a,str,b);
}
System.out.println();
}
public static void print(double a,String str,double b) {
if(b>0&&a!=0) { //虚部为正
if((a-Math.round(a))==0) {
System.out.print(Math.round(a));
}else {
System.out.print(a);
}
System.out.print("+");
if((b-Math.round(b))==0) {
System.out.print(Math.round(b));
}else {
System.out.print(b);
}
System.out.println("i");
}
if(b>0&&a==0) {
if((b-Math.round(b))==0) {
System.out.print(Math.round(b));
}else {
System.out.print(b);
}
}
if(b<0&&a!=0) { //虚部为负
if((a-Math.round(a))==0) {
System.out.print(Math.round(a));
}else {
System.out.print(a);
}
if((b-Math.round(b))==0) {
System.out.print(Math.round(b));
}else {
System.out.print(b);
}
System.out.println("i");
}
if(b<0&&a==0) {
if((b-Math.round(b))==0) {
System.out.print(Math.round(b));
}else {
System.out.print(b);
}
System.out.println("i");
}
}
}