用JAVA写一个两位数加减法程序
时间: 2023-11-27 22:05:02 浏览: 162
以下是一个使用Java编写的两位数加减法程序:
import java.util.Scanner;
public class AdditionSubtraction {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int a = (int) (Math.random() * 90) + 10; // 生成10-99之间的随机整数
int b = (int) (Math.random() * 90) + 10; // 生成10-99之间的随机整数
int operator = (int) (Math.random() * 2); // 随机生成0或1,用于确定是加法还是减法
if (operator == 0) { // 加法
System.out.print(a + " + " + b + " = ");
int result = scanner.nextInt();
if (result == a + b) {
System.out.println("答案正确!");
} else {
System.out.println("答案错误!");
}
} else { // 减法
if (a < b) { // 确保减数不小于被减数
int temp = a;
a = b;
b = temp;
}
System.out.print(a + " - " + b + " = ");
int result = scanner.nextInt();
if (result == a - b) {
System.out.println("答案正确!");
} else {
System.out.println("答案错误!");
}
}
}
}
运行结果可能如下所示:
25 + 68 = 93
93 + 27 = 120
67 - 41 = 26
15 - 27 = -12
23 - 10 = 13
...
阅读全文