Enum Text
无法运行...
TextDouble
0.05 + 0.01 = 0.06
1.0 - 0.42 = 0.58
4.015 * 100 = 401.5
123.3 / 100 = 1.233
X+Y=100200
300=X+Y
第一个加号具有拼接字符串的作用,第二个加号是加法的意思
生成四则运算
import java.util.Random;
import java.util.Scanner;
public class ArithmeticQuiz {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Random random = new Random();
int totalQuestions = 30;
int correctAnswers = 0;
for (int i = 0; i < totalQuestions; i++) {
// 随机生成两个操作数
int num1 = random.nextInt(100); // 0-99
int num2 = random.nextInt(100); // 0-99
// 随机选择一个运算符
char operator = getRandomOperator();
// 计算正确答案
int correctAnswer = calculate(num1, num2, operator);
// 提出问题并获取用户输入
System.out.printf("问题 %d: %d %c %d = ?\n", i + 1, num1, operator, num2);
System.out.print("请输入你的答案: ");
int userAnswer = scanner.nextInt();
// 判断用户答案是否正确
if (userAnswer == correctAnswer) {
System.out.println("回答正确!");
correctAnswers++;
} else {
System.out.printf("回答错误!正确答案是: %d\n", correctAnswer);
}
}
// 计算并显示正确率
double accuracy = (double) correctAnswers / totalQuestions * 100;
System.out.printf("你的正确率是: %.2f%%\n", accuracy);
scanner.close();
}
// 随机选择一个运算符
private static char getRandomOperator() {
char[] operators = {'+', '-', '*', '/'};
Random random = new Random();
return operators[random.nextInt(operators.length)];
}
// 计算结果
private static int calculate(int num1, int num2, char operator) {
switch (operator) {
case '+':
return num1 + num2;
case '-':
return num1 - num2;
case '*':
return num1 * num2;
case '/':
// 确保不出现除以零的情况
return num2 != 0 ? num1 / num2 : num1; // 如果 num2 为 0,返回 num1
default:
throw new IllegalArgumentException("未知的运算符: " + operator);
}
}
}
标签:random,num1,num2,int,动脑,System,动手,operator From: https://www.cnblogs.com/jackson12138/p/18437076