Java之简单的四则运算
简单的四则运算
请你编写程序实现能处理两个数的+、-、*、/、%的表达式程序。数据的输入/输出全部使用标准输入/输出,输入数据的第一行为你需要计算表达式的个数,从第2行开始,每一行为你计算的一个表达式,每行数据中没有空格,除%运算外的输入数据皆为float数,除%运算结果为整数外,其他都保留两位小数,每个表达式的结果使用一行输出。
输入测试用例:
4
1+2
3.12*4
7%3
1/3
用例输出结果:
3.00
12.48
1
0.33
提示:Scanner对象中的nextLine()方法是从当前位置读到回车换行接收,例如本输入数据的读数方法应该为:
int N = sc.nextInt();
sc.nextLine();//读到该行的结束,不需要的数据
String s = sc.nextLine();
import java.util.Scanner;
public class Main1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
sc.nextLine();
int i = 0;
while (i < n) {
String s = sc.nextLine();
float x, y;
String[] sa = s.split("[\\+ | - | \\* | % | /]");
if (s.indexOf("%") > -1) {
int a = Integer.parseInt(sa[0]);
int b = Integer.parseInt(sa[1]);
System.out.println(a % b);
i++;
continue;
}
else {
x = Float.parseFloat(sa[0]);
y = Float.parseFloat(sa[1]);
}
if(s.indexOf("+") > -1) {
System.out.printf("%.2f\n",x+y);
}
else if (s.indexOf("-") > -1) {
System.out.printf("%.2f\n",x-y);
}
else if (s.indexOf("*") > -1) {
System.out.printf("%.2f\n",x*y);
}
else if (s.indexOf("/") > -1) {
System.out.printf("%.2f\n",x/y);
}
i++;
}
}
}