课后总结
动手动脑
1:运行结果为
false
false
true
SMALL
MEDIUM
LARGE
枚举常量是单例:用 == 比较两个枚举常量可以判断它们是否是同一个实例。枚举类型不是基本数据类型:枚举的 getClass().isPrimitive() 返回 false,表明它们是对象而非原始类型。
从字符串转换:可以使用 valueOf 方法将字符串转换为对应的枚举常量,前提是字符串必须与枚举常量的名称完全一致,大小写敏感。枚举的遍历:可以通过 values() 方法获取所有枚举常量,适用于各种场景的遍历。
2:从大精度到小精度有精度损失,从小精度到大精度没有精度损失
3:
X+Y=100200
300=X+Y
因为由“”包括的为字符串
4:四则运算:package aq;
import java.util.Random;
public class MathQuizGenerator {
public static void main(String[] args) {
// 创建一个随机数生成器
Random random = new Random();
// 题目数量
int questionsCount = 30;
// 存储题目的数组
String[] questions = new String[questionsCount];
// 生成题目
for (int i = 0; i < questionsCount; i++) {
// 随机选择运算符
String operator;
int num1 = random.nextInt(100); // 生成0-99之间的随机数
int num2 = random.nextInt(100); // 生成0-99之间的随机数
switch (random.nextInt(4)) {
case 0:
operator = "+";
questions[i] = num1 + " " + operator + " " + num2;
break;
case 1:
operator = "-";
// 确保结果不为负数
if (num1 < num2) {
int temp = num1;
num1 = num2;
num2 = temp;
}
questions[i] = num1 + " " + operator + " " + num2;
break;
case 2:
operator = "*";
questions[i] = num1 + " " + operator + " " + num2;
break;
case 3:
operator = "/";
// 确保除数不为零
if (num2 == 0) {
num2 = 1; // 设置为1以避免除以零
}
questions[i] = num1 + " " + operator + " " + num2;
break;
default:
operator = "+"; // 默认运算符
questions[i] = num1 + " " + operator + " " + num2;
}
}
// 打印题目
System.out.println("今日四则运算题目:");
for (String question : questions) {
System.out.println(question);
}
}
}
5:原码:用最高位作为符号位(0表示正数,1表示负数),其余位表示数值。
正数的原码与其绝对值相同。
负数的原码是其绝对值的二进制表示,最高位为1。
反码:
正数的反码与原码相同。
负数的反码是其原码中符号位不变,其余位取反(0变1,1变0)。
补码
正数的补码与原码相同。
负数的补码是其反码加1。
ublic class NumberRepresentation {
public static void main(String[] args) {
int positiveNum = 5;
int negativeNum = -5
System.out.println("Positive Number: " + positiveNum);
printBinary(positiveNum);
System.out.println("Negative Number: " + negativeNum);
printBinary(negativeNum);
System.out.println("Positive Number Bitwise AND with 1: " + (positiveNum & 1));
System.out.println("Negative Number Bitwise OR with 5: " + (negativeNum | positiveNum));
System.out.println("Negative Number Bitwise XOR with -5: " + (negativeNum ^ -5));
}
public static void printBinary(int num) {
System.out.printf("Binary: %32s%n", Integer.toBinaryString(num));
System.out.printf("Inverting the bits (1's complement): %32s%n", Integer.toBinaryString(~num));
System.out.printf("Adding One (2's complement): %32s%n", Integer.toBinaryString(~num + 1));
}
通过观察程序的输出,可以确认 Java 确实采用了补码来表示整数。运行程序后,注意输出的二进制形式以及通过不同位操作的结果。
6:testdouble文件运行结果为
0.05 + 0.01 = 0.060000000000000005
1.0 - 0.42 = 0.5800000000000001
4.015 * 100 = 401.49999999999994
123.3 / 100 = 1.2329999999999999
意外,与常规逻辑不同,计算机由于浮点数的内部表示可能导致精度问题,特别是在涉及小数的计算时。例如,对于 0.05 + 0.01,理论上结果应该是 0.06,但有时计算机可能会因为浮点数表示不精确而导致微小的误差。double 类型的浮点运算不总是精确的,是由于二进制表示的局限性、精度限制、运算过程中误差的累积以及运算顺序的影响。建议使用 BigDecimal 类来处理浮点数的问题。