输入数学表达式并计算出结果(包括小数)

输入数学表达式并计算出结果(包括小数)

萨达斯

要求如下:

/**
 * 输入一个数学计算表达式,如:1+2
 * 然后输出计算后的结果:1+2=3
 * 这里计算表达式只计算一次即可,可以使用加减乘除任意一个,可以进行小数运算。
 */

代码如下:

public class Test07 {
	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		System.out.println("请输入算式:");
		String input = scan.nextLine();//接收数据
		int index = -1;
		if((index=input.indexOf("+"))>0){//加法运算
			double[] result=check(input,index);
//			double num1 = Double.parseDouble(input.substring(0, index));
//			double num2 = Double.parseDouble(input.substring(index+1));
			System.out.println(input + "=" + (result[0]+result[1]));		
		}else if((index=input.indexOf("-"))>0){//减法运算
			double[] result=check(input,index);
//			double num1 = Double.parseDouble(input.substring(0, index));
//			double num2 = Double.parseDouble(input.substring(index+1));
			System.out.println(input + "=" + (result[0]-result[1]));		
			
		}else if((index=input.indexOf("*"))>0){//减法运算
			double[] result=check(input,index);
//			double num1 = Double.parseDouble(input.substring(0, index));
//			double num2 = Double.parseDouble(input.substring(index+1));
			System.out.println(input + "=" + (result[0]*result[1]));		
			
		}else if((index=input.indexOf("/"))>0){//减法运算
			double[] result=check(input,index);
//			double num1 = Double.parseDouble(input.substring(0, index));
//			double num2 = Double.parseDouble(input.substring(index+1));
			if(result[1] == 0){
				System.out.println("除数为0,输入错误");
			}else{
				System.out.println(input + "=" + (result[0]/result[1]));		
			}
		}
	}
	//可以封装方法
	public static double[] check(String input,int index){
		double[] result = new double[2];
		result[0] = Double.parseDouble(input.substring(0,index));
		result[1] = Double.parseDouble(input.substring(index+1));
		return result;
	}
}

输出结果为:

请输入算式:
2.5/2.6
2.5/2.6=0.9615384615384615


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

荒--

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值