课后作业2
一、动手动脑
(1)

编译后发现结果有较小偏差,用double计算是无法得出精确值的
(2)
第一行代码,由于第一个是字符串,同时用了“+”,后面直接自动相连,不进行计算
第二行代码,先进行计算,后面才是字符串,所以并未直接相连
二、课后实验性问题
(1)带着疑问看故事
估计需要半个小时可以完成,实际上用的时间长得多,还是需要再熟练
import java.util.Random;
public class Math {
public static void main(String[] args) {
Random rnd = new Random();
int total = 30;
int addCount = 5, subCount = 5, mulCount = 10, divCount = 10;
String[] questions = new String[total];
String[] answers = new String[total];
int idx = 0;
// 加法
for (int i = 0; i < addCount; i++) {
int a = rnd.nextInt(101); // 0..100
int b = rnd.nextInt(101);
questions[idx] = String.format("%d) %d + %d = ", idx + 1, a, b);
answers[idx] = String.valueOf(a + b);
idx++;
}
// 减法
for (int i = 0; i < subCount; i++) {
int a = rnd.nextInt(101);
int b = rnd.nextInt(101);
questions[idx] = String.format("%d) %d - %d = ", idx + 1, a, b);
answers[idx] = String.valueOf(a - b);
idx++;
}
// 乘法
for (int i = 0; i < mulCount; i++) {
int a = rnd.nextInt(21); // 0..20
int b = rnd.nextInt(21);
questions[idx] = String.format("%d) %d × %d = ", idx + 1, a, b);
answers[idx] = String.valueOf(a * b);
idx++;
}
// 除法
for (int i = 0; i < divCount; i++) {
int divisor = rnd.nextInt(12) + 1; // 1..12
int quotient = rnd.nextInt(21); // 0..20
int dividend = divisor * quotient; // 保证整除
questions[idx] = String.format("%d) %d ÷ %d = ", idx + 1, dividend, divisor);
answers[idx] = String.valueOf(quotient);
idx++;
}
// 打印所有题目
System.out.println("=== 试题 ===");
for (String q : questions) {
System.out.println(q);
}
}
}
(2)课后作业3
import java.util.Random;
public class RandomStr {
public static void main(String[] args) {
Random rnd = new Random();
StringBuilder code = new StringBuilder();
for (int i = 0; i < 6; i++) {
int type = rnd.nextInt(3); // 0=数字, 1=大写字母, 2=小写字母
char ch;
if (type == 0) {
ch = (char) ('0' + rnd.nextInt(10)); // '0' ~ '9'
} else if (type == 1) {
ch = (char) ('A' + rnd.nextInt(26)); // 'A' ~ 'Z'
} else {
ch = (char) ('a' + rnd.nextInt(26)); // 'a' ~ 'z'
}
code.append(ch);
}
System.out.println("验证码: " + code.toString());
}
}

浙公网安备 33010602011771号