编程练习题
基础篇课后习题答案,只是练习完后用来分享,不一定是最佳代码,但是保证每个都能运行,如有错误,欢迎提出,如有更好的答案,欢迎讨论。
2.5(财务应用程序:计算小费)
代码如下(示例):
import java.util.Scanner;
public class Test01 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the subtotal and a gratuity rate: ");
int subtotal = sc.nextInt();
int rate = sc.nextInt();
System.out.print("The gratuity is $" + rate/10.0 + " and total is $" + (subtotal+rate/10.0));
sc.close();
}
}
Enter the subtotal and a gratuity rate: 10 15
The gratuity is $1.5 and total is $11.5
2.6(求一个整数各位数的和)
代码如下(示例):
import java.util.Scanner;
public class Test02 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number between 0 and 1000: ");
int a = sc.nextInt();
System.out.print("The sum of the digits is " + (a/100 + (a/10)%10 + a%10));
sc.close();
}
}
Enter the number between 0 and 1000: 999
The sum of the digits is 27
2.7(求出年数)
代码如下(示例):
import java.util.Scanner;
public class Test03 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of minutes: ");
long a = sc.nextLong();
System.out.print(a + " minutes is approximately " + a/(60*24*365) + " years and " + (a/(60*24))%365 + " days");
sc.close();
}
}
Enter the number of minutes: 1000000000
1000000000 minutes is approximately 1902 years and 214 days
2.13(财务应用程序:复利值)
代码如下(示例):
import java.util.Scanner;
public class Test04 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the monthly saving amount: ");
double a = sc.nextDouble();
double b = a;
double result = 0;
for(int i = 0;i < 5;i++) {
result = (a + b)*(1+0.00417);
b = result;
}
System.out.printf("After the sixth month, the account value is $" + "%.2f",result);
sc.close();
}
}
Enter the monthly saving amount: 100
After the sixth month, the account value is $608.39
算出来和答案有点小偏差
2.15(几何:两点间距离)
代码如下(示例):
import java.util.Scanner;
public class Test05 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter x1 and y1: ");
double x1 = sc.nextDouble();
double y1 = sc.nextDouble();
System.out.print("Enter x2 and y2: ");
double x2 = sc.nextDouble();
double y2 = sc.nextDouble();
double result = Math.pow(((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1)),0.5);
System.out.printf("The distance between the two points is " + result);
sc.close();
}
}
Enter x1 and y1: 1.5 -3.4
Enter x2 and y2: 4 5
The distance between the two points is 8.764131445842194
总结
第二章大致感受了基本程序设计,不说了上课去了。