第二章 基本程序设计 课后习题答案

课后习题

2.1 CelsiusChangeFahrenheit.java

import java.util.Scanner;

public class CelsiusChangeFahrenheit {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter a degree in Celsius: ");
        double Celsius = input.nextDouble();
        double Fahrenheit = Celsius * (9.0 / 5) + 32;
        System.out.println(Celsius + " Celsius is " + Fahrenheit + " Fahrenheit");
    }
}

2.2 CylinderVolume.java

import java.util.Scanner;

public class CylinderVolume {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter the radius and length of cylinder:");
        double radius = input.nextDouble();
        double length = input.nextDouble();
        double area = radius * radius * Math.PI;
        double volume = area * length;
        System.out.println("The area is "+ area);
        System.out.println("The volume is "+volume);
    }
}

2.3 FeetToMeters.java

import java.util.Scanner;

public class FeetToMeters {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter a value for feet:");
        double feet = input.nextDouble(), meters;
        meters = feet * 0.305;
        System.out.println(feet + " feet is " + meters+" meters");
    }
}

2.4 PoundToKilograms.java

import java.util.Scanner;

public class PoundToKilograms {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter a number in pounds:");
        double pound = input.nextDouble(),kilograms;
        kilograms = pound * 0.454;
        System.out.println(pound+" pounds is "+kilograms+" kilograms");
    }
}

2.5 CalculateRate.java

import java.util.Scanner;

public class CalculateRate {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter the subtotal and a gratuity rate: ");
        double cost = input.nextDouble();
        double rate = input.nextDouble();
        rate = cost * rate / 100;
        double totalcost = cost + rate;
        System.out.println("The gratuity is $ " + rate + " and total is $"+totalcost );
    }
}

2.6 SumOfEachIntegers.java

import java.util.Scanner;

public class SumOfEachIntegers {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter a number between 0 and 1000: ");
        int number = input.nextInt();
        int ge, shi, bai, sum;
        ge = number % 10;
        shi = (number / 10) % 10;
        bai = (number / 100);
        sum = ge + shi + bai;
        System.out.println("The sum of the digits is : " + sum);
    }
}

2.7 NumberOfYears.java

import java.util.Scanner;

public class NumberOfYears {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter the number of minutes: ");
        int minutes = input.nextInt();
        int years = minutes / (24 * 60 * 365);
        int remainminute = minutes % (24 * 60 * 365);
        int days = remainminute / (24 * 60);
        System.out.println(minutes + " minutes is approximately " + years + " years and " + days + " days");
    }
}

2.8 CurrentTime.java

import java.util.Scanner;

public class CurrentTime {
    public static void main(String[] args) {
        //Obtain the total milliseconds since midnight, Jan 1, 1970
        long totalMillliseconds = System.currentTimeMillis();
        long totalSeconds = totalMillliseconds / 1000;
        long currentSecond = totalSeconds % 60;
        long totalMinutes = totalSeconds / 60;
        long currentMinute = totalMinutes % 60;
        long totalHours = totalMinutes / 60;
        Scanner input = new Scanner(System.in);
        System.out.print("Enter the time zone offset to GMT: ");
        long zone = input.nextLong();
        long currentHour = (totalHours % 24) + zone;
        System.out.println("The current time is " + currentHour + ":"
                + currentMinute + ":" + currentSecond + " GMT");
    }
}

2.9 Acceleration.java

import java.util.Scanner;

public class Acceleration {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter v0 , v1 and t: ");
        float v0 = input.nextFloat();
        float v1 = input.nextFloat();
        float t = input.nextFloat();
        float acc = (v1 - v0) / t;
        System.out.println("The average acceleration is : " + acc);
    }
}

2.10 CalculateEnergy.java

import java.util.Scanner;

public class CalculateEnergy {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter the amount of water in kilograms: ");//xx千克重的水
        double kilogram = input.nextDouble();
        System.out.print("Enter the initial temperature: ");//水的起始温度
        double temperature01 = input.nextDouble();
        System.out.print("Enter the final temperature: ");//水的最终温度
        double temperature02 = input.nextDouble();
        double energy = kilogram * (temperature02 - temperature01) * 4184;
        System.out.println("The energy needed is :" + energy);//计算能量
    }
}

2.11 Demographic.java

import java.util.Scanner;

public class Demographic {
    public static void main(String[] args) {
        System.out.println("The current population of American is 321 032 486.");
        System.out.print("Enter the number of years: ");//键入年份
        Scanner input = new Scanner(System.in);
        double year = input.nextDouble();
        double Nowpopulation = 312032486;
        double yearsecond = year * 60 * 60 * 24 * 365;//当前人口数量
        double born = yearsecond / 7;//这里不做取整处理
        double dead = yearsecond / 13;
        double immigration = yearsecond / 45;
        double Addpopulation = born - dead + immigration;
        Nowpopulation = Nowpopulation + Addpopulation;
        System.out.println("The population in 5 years is :" + Nowpopulation);
    }
}

2.12 TheRunwayLength.java

import java.util.Scanner;

public class TheRunwayLength {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter speed and acceleration: ");
        double speed = input.nextDouble();
        double acceleration = input.nextDouble();
        double length = (speed * speed) / (2 * acceleration);
        System.out.println("The minumum runway length for this airplane is : " + length);
    }
}

2.13 CompoundValue.java

import java.util.Scanner;

public class CompoundValue {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter the monthly saving amount: ");
        double amount = input.nextDouble(),rate = 1.00417,add = 0;
        amount *= rate;
        for (int i = 1;i<6;i++) {
            amount = (amount + 100) * rate;
        }
        System.out.println("After sixth month, the account value is $" + amount);
    }
}

2.14 CalculateBMI.java

import java.util.Scanner;

public class CalculateBMI {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter weight in pounds: ");
        double pound = input.nextFloat();
        System.out.print("Enter height in inches: ");
        double inches = input.nextFloat();
        double kg = pound * 0.45359237;
        double meter = inches * 0.0254;
        double BMI = kg / (Math.pow(meter, 2));
        System.out.println("BMI is : " + BMI);
    }
}

2.15 TwoPointsDistance.java

import java.util.Scanner;

public class TwoPointsDistance {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter x1 and y1: ");
        double x1 = input.nextDouble();
        double y1 = input.nextDouble();
        System.out.print("Enter x2 and y2: ");
        double x2 = input.nextDouble();
        double y2 = input.nextDouble();
        double a = Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2);
        double distance = Math.pow(a, 0.5);
        System.out.println("The distance between the two points is : " + distance);
    }
}

2.16 HexagonalArea.java

import java.util.Scanner;

public class HexagonalArea {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter the length of side: ");
        double length = input.nextDouble();
        double area = (3 * Math.pow(3, 0.5) / 2) * length * length;
        System.out.println("The area of the hexagon is : " + area);
    }
}

2.17 ColdTemperature.java

import java.util.Scanner;

public class ColdTemperature {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter the temperature in Fahrenheit between -58°F and 41°F: ");
        double ta = input.nextDouble();
        System.out.print("Enter the wind speed(>=2) in miles per hour: ");
        double windspeed = input.nextDouble();
        double twc = 35.74 + 0.6215 * ta - 35.75 * Math.pow(windspeed, 0.16) + 0.4275 * ta * Math.pow(windspeed, 0.16);
        System.out.println("The wind chill index is : " + twc);
    }
}

2.18 PrintTable.java

public class PrintTable {
    public static void main(String[] args) {
        System.out.println("a\tb\tpow(a,b)");
        double a, b = 2, pow;
        for (a = 1; a <= 5; a++, b++) {
            pow = Math.pow(a, b);
            System.out.print((int) a + "\t");
            System.out.print((int) b + "\t");
            System.out.println((int) pow + "\t");
        }
    }
}

2.19 TriangularArea.java

import java.util.Scanner;

public class TriangularArea {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter the coordinates of three points separated by spaces \n " +
                "like x1 y1 x2 y2 x3 y3: ");
        double x1 = input.nextDouble();    double y1 = input.nextDouble();
        double x2 = input.nextDouble();    double y2 = input.nextDouble();
        double x3 = input.nextDouble();    double y3 = input.nextDouble();
        double line1 = Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2);
        double line2 = Math.pow(x3 - x2, 2) + Math.pow(y3 - y2, 2);
        double line3 = Math.pow(x3 - x1, 2) + Math.pow(y3 - y1, 2);
        double s = (line1 + line2 + line3) / 2;
        double area = Math.pow(s * (s - line1) * (s - line2) * (s - line3), 0.5);
        System.out.println("The area of the triangle is 33.6");
    }
}

2.20 CalculationOfInterest.java

import java.util.Scanner;

public class CalculationOfInterest {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter the balcance and interest rate(e.g.,3 for 3%): ");
        double balance = input.nextDouble();
        double rate = input.nextDouble(); //第一次表示年利率
        rate = balance * (rate / 1200);//表示利息值
        System.out.println("The interest is : " + rate);
    }
}

2.21 ReturnOnInvestment.java

import java.util.Scanner;

public class ReturnOnInvestment {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter investment amount: ");//投资金额
        double amount = input.nextDouble();
        System.out.print("Enter annual interest rate in percentage: ");//年利率
        double rate = input.nextDouble();
        System.out.print("Enter number of years: ");//存款年数
        double years = input.nextDouble();
        amount = amount * Math.pow((1 + rate / 1200), years * 12);
        System.out.println("Future value is $" + amount);
    }
}

2.22 MonetaryUnit.java

import java.util.Scanner;

public class MonetaryUnit {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter an amount in int, for example 1156: ");
        int amount = input.nextInt();
        int dollar = amount / 100;
        int pennies = amount % 100;
        System.out.println("Your amount is " + dollar +
         " dollar " + pennies + " pennies");
    }
}

2.23 DrivingCost.java

import java.util.Scanner;

public class DrivingCost {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter the driving distance: ");
        double distance = input.nextDouble();
        System.out.print("Enter miles per gallon: ");
        double miles = input.nextDouble();
        System.out.print("Enter price per gallon: ");
        double price = input.nextDouble();
        double cost = price * (distance / miles);
        System.out.println("The cost of driving is $" + cost);
    }
}

关键术语

algorithm(算法)
assignment operator(=)(赋值运算符)
assignment statement(赋值语句)
byte type(字节类型)
casting(类型转换)
constant(常量)
data type(数据类型)
declare variables(声明变量)
decrement operator(- -)(自减操作符)
double type(双精度类型)
expression(表达式)
final keyword(final关键字)
float type(浮点类型)
floating-point number(浮点数)
identifier(标识符)
increment operator(++)(自增操作符)
incremental development and testing(增量式开发和测试)
int type(整数类型)
IPO(输入 - 处理 - 输出)
literal(字面值)
long type(长整型类型)
narrowing(of types)(缩小类型)
operands(操作数)
operator(操作符)
overflow(上溢)
postdecrement(后置自减)
postincrement(后置自增)
predecrement(前置自减)
preincrement(前置自增)
primitive date type(基本数据类型)
pseudocode(伪代码)
requirement specification(需求规范)
scope of a variable(变量范围)
short type(短整型类型)
specific import(明确导入)
system analysis(系统分析)
system design(系统设计)
underflow(下溢)
UNIX epoch(UNIX时间戳)
variable(变量)
widening(of types)(扩展类型)
wildcard import(通配符导入)

本章小结

1.标识符是程序中用于命名诸如变量、常量、方法、类、包等元素的名称。
2.标识符是由字母、数字、下划线(_)和美元符号($)构成的字符序列。标识符必须以字母或下划线开头,不能以数字开头。标识符不能是保留字。标识符可以为任意长度。
3.变量用于存储程序中的数据。声明变量就是告诉编译器该变量可以存储何种数据类型。
4.有两种类型的import语句:明确导入和通配符导入。明确导入是在import语句中指定导入单个类;通配符导入将包中所有的类导入。
5.在Java中,等号(=)被用作赋值操作符。
6.方法中声明的变量必须在使用前被赋值。
7.命名常量(或简称为常量)表示从不改变的数据。
8.用关键字final声明命名常量。
9.Java提供四种整数类型(byte、short、int、long)表示四种不同大小范围的整数。
10.Java提供两种浮点类型(float、double)表示两种不同精度的浮点数。
11.Java提供操作符完成数值晕眩:加号(+)、减号(-)、乘号()、除号(/)和求余符号(%)。
12.整数运算(/)得到的结果是一个整数。
13.Java表达式中的数值操作符和算术表达式中的使用方法是完全一致的。
14.Java提供扩展赋值操作符:+=(加法赋值)、-=(减法赋值)、
*=(乘法赋值)、/=(除法赋值)以及%=(求余赋值)。
15.自增操作符(++)和自减操作符(--)分别对变量加1或减1。
16.当计算的表达式中有不同类型的值时,Java会自动地将操作数转换为恰当的类型。
17.可以使用(type)value这样的表示法显式地将数值从一个类型转换到另一个类型。
18.将一个较小范围类型的变量转换为较大范围类型的变量称为扩展类型。
19.将一个较大范围类型的变量转换为较小范围类型的变量称为缩小类型。
20.扩展类型不需要显式转换,可以自动完成。缩小类型必须显式完成。
21.在计算机科学中,1970年1月1日午夜零点称为UNIX时间戳。

posted @ 2021-10-07 16:43  Wozen  阅读(119)  评论(0)    收藏  举报