一、J1_26_1
输入一个百分制的成绩 t,将其转换成对应的等级然后输出,
具体转换规则如下:
90~100 为A
80~89 为 B
70~79 为 C
60~69 为 D
0~59 为 E
要求:如果输入数据不在 0~100范围内,请输出一行:“Score is error!”。
代码如下:
public class Week01 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入成绩(1-100):");
int t = sc.nextInt();
while (!(t >= 0) || !(t <= 100)) {
System.out.println("输入的成绩不在范围,请重新输入:");
t = sc.nextInt();
}
if (t <= 59) {
System.out.println("E");
} else if (t <= 69) {
System.out.println("D");
} else if (t <= 79) {
System.out.println("C");
} else if (t <= 89) {
System.out.println("B");
} else if (t <= 100) {
System.out.println("A");
}
}
}
二、J1_26_2
数列的定义如下: 数列的第一项为 n,以后各项为前一项的平方根,输出数列的前 m 项的和。
要求:数列的各项均为正数。
代码如下:
public class Week02 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("输入n和m,用空格隔开:");
String inputStr = sc.nextLine();
String[] str = inputStr.split(" ");
int n = Integer.parseInt(str[0]);// 数列的第一项为n
int m = Integer.valueOf(str[1]);// 指定前m项
double sum = 0;
double temp = n;
for (int i = 0; i < m; i++) {
sum += temp;
temp = Math.sqrt(temp);// 求出每一项的值;
}
sum = (Math.round(sum * 100));// 四舍五入,然后取整,确保精度保留2位小数
if (sum % 100 == 0) {
System.out.println(sum / 100 + ".00"); // 如2*100=200,变为2.00
} else if (sum % 10 == 0) {
System.out.println(sum / 100.0 + "0"); // 如1.5*100=150.变为1.50
} else
System.out.println(sum / 100.0);// 如3.25*100=325,变为3.25
}
}
二、J1_26_3
多项式的描述如下:1 - 1/2 + 1/3 - 1/4 + 1/5 - 1/6 + …,
现在要求出该多项式 的前 n 项的和。
要求:结果保留两位小数。
代码如下:
public class Week03 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入n:");
double n = sc.nextInt();
double sum = 0;// 用来保存该多项式的和
for (double i = 1; i <= n; i++) {
if (i % 2 == 0) {
sum -= (1 / i);
} else {
sum += (1 / i);
}
}
System.out.println("该多项式的和为:" + String.format("%.2f", sum));
}
}