import java.util.Scanner;
public class calculator {
public static void main(String[ ] args){
//输入数字个数
Scanner input = new Scanner(System.in);
System.out.println("请输入数字个数:");
int numcount = input.nextInt();
//输入数字
System.out.println("请输入" + numcount + "个数字:");
double[ ] numbers = new double[numcount];
for (int i = 0 ; i < numcount; i++){
numbers[i] = input.nextDouble();
}
//输入运算符
System.out.println("请输入运算符(+,-,*,/):");
String operator = input.next();
double result = 0 ;
//执行运算
if (operator.equals("+")) {
result = add(numbers);
} else if (operator.equals("-")) {
result = subtract(numbers);
} else if (operator.equals("*")) {
result = multiply(numbers);
} else if (operator.equals("/")) {
result = divide(numbers);
} else {
System.out.println("无效运算符");
return;
}
System.out.println("结果:" + result);
}
// 加法
public static double add(double[] numbers) {
double sum = 0;
for (double num : numbers) {
sum += num;
}
return sum;
}
// 减法
public static double subtract(double[] numbers) {
double difference = numbers[0];
for (int i = 1; i < numbers.length; i++) {
difference -= numbers[i];
}
return difference;
}
// 乘法
public static double multiply(double[] numbers) {
double product = 1;
for (double num : numbers) {
product *= num;
}
return product;
}
// 除法
public static double divide(double[] numbers) {
double quotient = numbers[0];
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] == 0) {
System.out.println("除数不能为0");
System.exit(0);
}
quotient /= numbers[i];
}
return quotient;
}
}