Java语言程序设计(基础篇)原书第10版编程练习题第二章(部分)个人答案

编程练习题

基础篇课后习题答案,只是练习完后用来分享,不一定是最佳代码,但是保证每个都能运行,如有错误,欢迎提出,如有更好的答案,欢迎讨论。


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

总结

第二章大致感受了基本程序设计,不说了上课去了。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值