您的位置:首页 > 编程语言 > Java开发

stanford编程方法——习题答案(the art and science of java)——chapter03

2011-03-12 23:31 801 查看
-------------------------------------------------------------------------------
Chapter 03 Expressions
Review questions
-------------------------------------------------------------------------------
1 What are the two attributes that define a data type ?
Answer:
domain
set of operations
-------------------------------------------------------------------------------
2 Identify which of the following are legal constants in Java. For the ones that are legal, indicate whether they are integers or floating-point constants.
a) 42 g) 1,000,000
b) -17 h) 3.1415926
c) 2+3 i) 123456789
d) -2.3 j) 0.000001
e) 20 k) 1.1E+11
f) 2.0 l) 1.1X+11
Answer:
a) 42 iconst g) 1,000,000 illegal
b) -17 iconst h) 3.1415926 fconst
c) 2+3 illegal i) 123456789 iconst
d) -2.3 fconst j) 0.000001 fconst
e) 20 iconst k) 1.1E+11 fconst
f) 2.0 fconst l) 1.1X+11 illegal
-------------------------------------------------------------------------------
3. Rewrite the following floating-point constants in Java’s form for scientific notation:
a) 6.02252 x 1023
b) 29979250000.0
c) 0.00000000529167
d) 3.1415926535
(By the way, each of these constants represents an approximation of an important value from chemistry, physics, or mathematics: (a) Avogadro’s number, (b) the
speed of light in centimeters per second, (c) the Bohr radius in centimeters, and (d) the mathematical constant π. In the case of π, there is no advantage in using the scientific notation form, but it is nonetheless possible and you should know how to do so.)
Answer:
a) 6.02252 x 1023 6.16103796E+3
b) 29979250000.0 2.997925E+11
c) 0.00000000529167 5.29167E-9
d) 3.1415926535 3.1415926535E-0
-------------------------------------------------------------------------------
4. Indicate which of the following are legal variable names in Java:
a) x g) total output
b) formula1 h) aReasonablyLongVariableName
c) average_rainfall i) 12MonthTotal
d) %correct j) marginal-cost
e) short k) b4hand
f) tiny l) _stk_depth
Answer:
a) x ok g) total output not
b) formula1 ok h) aReasonablyLongVariableName ok
c) average_rainfall ok i) 12MonthTotal not
d) %correct not j) marginal-cost not
e) short not k) b4hand ok
f) tiny not l) _stk_depth ok
-------------------------------------------------------------------------------
5. Indicate the values and types of the following expressions:
a) 2 + 3 d) 3 * 6.0
b) 19 / 5 e) 19 % 5
c) 19.0 / 5 f) 2 % 7
Answer:
a) 2 + 3 5, int d) 3 * 6.0 18.0, float
b) 19 / 5 3, int e) 19 % 5 4, int
c) 19.0 / 5 3.8, float f) 2 % 7 2, int
-------------------------------------------------------------------------------
6. What is the difference between the unary minus operator and the binary subtraction operator?
Answer:
precedence
-------------------------------------------------------------------------------
7. By applying the appropriate precedence rules, calculate the result of each of the following expressions:
a) 6 + 5 / 4 - 3
b) 2 + 2 * (2 * 2 - 2) % 2 / 2
c) 10 + 9 * ((8 + 7) % 6) + 5 * 4 % 3 * 2 + 1
d) 1 + 2 + (3 + 4) * ((5 * 6 % 7 * 8) - 9) - 10
Answer:
a) 6 + 5 / 4 - 3
6 + 1 -3
7 - 3
4
b) 2 + 2 * (2 * 2 - 2) % 2 / 2
2 + 2 * (4 - 2) % 2 / 2
2 + 2 * 2 % 2 / 2
2 + 4 % 2 / 2
2 + 0 / 2
2 + 0
2
c) 10 + 9 * ((8 + 7) % 6) + 5 * 4 % 3 * 2 + 1
10 + 9 * (15 % 6) + 5 * 4 % 3 * 2 + 1
10 + 9 * 3 + 5 * 4 % 3 * 2 + 1
10 + 27 + 5 * 4 % 3 * 2 + 1
10 + 27 + 20 % 3 * 2 + 1
10 + 27 + 2 * 2 + 1
10 + 27 + 4 + 1
37 + 4 + 1
41 + 1
42
d) 1 + 2 + (3 + 4) * ((5 * 6 % 7 * 8) - 9) - 10
1 + 2 + 7 * ((5 * 6 % 7 * 8) - 9) - 10
1 + 2 + 7 * ((30 % 7 * 8) - 9) - 10
1 + 2 + 7 * ((2 * 8) - 9) - 10
1 + 2 + 7 * (16 - 9) - 10
1 + 2 + 7 * 7 - 10
1 + 2 + 49 - 10
3 + 49 - 10
52 - 10
42
-------------------------------------------------------------------------------
8. If the variable k is declared to be of type int, what value does k contain after the program executes the assignment statement
k = (int) 3.14159;
What value would k contain after the assignment statement
k = (int) 2.71828;
Answer:
k = (int) 3.14159; k = 3;
k = (int) 2.71828; k = 2;
-------------------------------------------------------------------------------
9. In Java, how do you specify conversion between numeric types?
Answer:
variable = (type) (expression)
-------------------------------------------------------------------------------
10. What idiom would you use to multiply the value of the variable cellCount by 2?
Answer:
variable *= 2;
-------------------------------------------------------------------------------
11. What is the most common way in Java to write a statement that has the same effect as the statement
x = x + 1;
Answer:
x++ ++x
// x += 1
-------------------------------------------------------------------------------
Programming exercises
1. Extend the InchesToCentimeters program given in Figure 3-2 so that it reads in
two input values: the number of feet, followed on a separate line by the number of
inches. Here is a sample run of the program:

/*
* File: InchesToCentimeters.java
* ------------------------------
* This program converts inches to centimeters.`
*/
import acm.program.*;

public class InchesToCentimeters extends ConsoleProgram {
public void run() {
println("This program converts inches to centimeters.");
double inches = readDouble("Enter value in inches: ");
double cm = inches * CENTIMETERS_PER_INCHE;
println(inches + "in = " + cm + "cm");

}

private static final double CENTIMETERS_PER_INCHE = 2.54;
}


----------------------------------------------------------------------------------------------------------------

2. Write a program that reads in two numbers: an account balance and an annual
interest rate expressed as a percentage. Your program should then display the new
balance after a year. There are no deposits or withdrawals—just the interest payment.
Your program should be able to reproduce the following sample run:

/*
* File: Interest.java
* --------------------
* This program calculate the interest.
*/
import acm.program.*;

public class Interest extends ConsoleProgram {
public void run() {
println("Interest calculation program");
double balance = readDouble("Enter starting balance: ");
double interest_rate = readDouble("Enter annual interest rate: ");
double sum = balance * ( (interest_rate + 100.0)/ 100 );
println("Balance after one year = " + sum);
}
}


----------------------------------------------------------------------------------------------------------------

3. Extend the program you wrote in Exercise 2 so that it also displays the balance after
two years have elapsed, as shown in the following sample run:

Note that the interest used in this example is compounded annually, which means the
interest from the first year is added back to the bank balance and is therefore itself
subject to interest in the second year. In the first year, the $6,000 earns 4.25%
interest, or $255. In the second year, the account earns 4.25% interest on the entire
$6,255.

/*
* File: Interest2.java
* --------------------
* This program calculate the interest.
*/
import acm.program.*;

public class Interest2 extends ConsoleProgram {
public void run() {
println("Interest calculation program");
double balance = readDouble("Enter starting balance: ");
double interest_rate = readDouble("Enter annual interest rate: ");
double sum = balance * ( (interest_rate + 100.0)/ 100 );
double sum2 = sum * ( (interest_rate + 100.0)/ 100 );
println("Balance after one year = " + sum);
println("Balance after two year = " + sum2);
}
}


-----------------------------------------------------------------------------------------------------------

4. Write a program that asks the user for the radius of a circle and then computes the
area of that circle (A) using the formula
A = PI*r^2
Note that there is no “raise to a power” operator in Java. Given the arithmetic
operators you know Java has, how can you write an expression that achieves the
desired result?

/*
* File: CalculateAreaOfCircle.java
* --------------------------------
* This program computes the area of cricle A.
*	A = PI * r^2
*/
import acm.program.*;

public class CalculateAreaOfCircle extends ConsoleProgram {
public void run() {
println("This program computes the area of circle");
double radius = readDouble("Enter the radius of circle: ");
double area = PI * radius * radius;
println("the area of circle is : " + area);
}
private static final double PI = 3.1415926525;
}


----------------------------------------------------------------------------------------------------------

5. Write a program that reads in a temperature in degrees Fahrenheit and returns the
corresponding temperature in degrees Celsius. The conversion formula is
C = 5/9 (F – 32)
The following is a sample run of the program:

If you write this program carelessly, the answer always comes out 0. What bug
causes this behavior?

/*
* File: FahrenheitToCelsius.java
* ------------------------------
* This program converts Farhrenheit to Celsius.
*/
import acm.program.*;

public class FahrenheitToCelsius extends ConsoleProgram{
public void run() {
println("This program converts Fahrenheit to Celsius.");
double fahr = readDouble("Enter Fahrenheit tempreature: ");
double cels = 5.0 / 9 * (fahr - 32);
println("Celsius equivalent = " + cels);
}
}


--------------------------------------------------------------------------------------------------------

6. In Norton Juster’s children’s story The Phantom Tollbooth, the Mathemagician gives
Milo the following problem to solve:
4 + 9 - 2 * 16 + 1 / 3 * 6 - 67 + 8 * 2 - 3 + 26 - 1 / 34 + 3 / 7 + 2 - 5
According to Milo’s calculations, which are corroborated by the Mathemagician, this
expression “all works out to zero.” If you do the calculation, however, the
expression comes out to zero only if you start at the beginning and apply all the
operators in strict left-to-right order. What would the answer be if the
Mathemagician’s expression were evaluated using Java’s precedence rules? Write a
program to verify your calculation.

/*
* File: PhantomTollbooth.java
* ---------------------------
* This program calculate the Milo's calculations.
*/
import acm.program.*;

public class PhantomTollbooth extends ConsoleProgram {
public void run() {
int sum1 = 4 + 9 - 2 * 16 + 1 / 3 * 6 - 67 + 8 * 2 - 3 + 26 - 1 / 34 + 3 / 7 + 2 - 5;
int sum2 = (((((4 + 9 - 2) * 16 + 1) / 3 * 6 - 67 + 8) * 2 - 3 + 26 - 1) / 34 + 3) / 7 + 2 - 5;
println("sum1: "+ sum1 + " sum2: " + sum2);
}
}


-----------------------------------------------------------------------------------------------------------

7. Write a program that converts a metric weight in kilograms to the corresponding
English weight in pounds and ounces. The conversion factors you need are
1 kilogram = 2.2 pounds
1 pound = 16 ounces

/*
* File: KilogramsToPoundsAndOunces.java
* -------------------------------------
* This program converts a metric weight in kilograms
* to the corresponding English weith in pounds and ounces.
*/
import acm.program.*;

public class KilogramsToPoundsAndOunces extends ConsoleProgram {
public void run() {
println("This program converts kilograms to pounds and ounces.");
double kg = readDouble("Enter  weight in kilograms: ");
double pounds = kg * POUNDS_PER_KILOGRAM;
double ounces = pounds * OUNCES_PER_POUND;
println(kg + "kilograms = " + pounds + "pounds");
println(kg + "kilograms = " + ounces + "ounces");
}
private static final double POUNDS_PER_KILOGRAM = 2.2;
private static final double OUNCES_PER_POUND = 16;
}


-----------------------------------------------------------------------------------------------------------

8. Write a program that computes the average of four integers.

/*
* File: AverageOfFourIntegers.java
* --------------------------------
* This program computes the avaerage of four integers:
*/
import acm.program.*;

public class AverageOfFourIntegers extends ConsoleProgram {
public void run () {
println("This program computes the average of four integers.");
int n1 = readInt("Enter integer one: ");
int n2 = readInt("Enter integer two: ");
int n3 = readInt("Enter integer three: ");
int n4 = readInt("Enter integer four: ");
double average = (n1 + n2 + n3 + n4) / 4.0;
println("The average of four integgers: " + average);
}
}


-----------------------------------------------------------------------------------------------------------

9. There’s an old nursery rhyme that goes like this:
As I was going to St. Ives,
I met a man with seven wives,
Each wife had seven sacks,
Each sack had seven cats,
Each cat had seven kits:
Kits, cats, sacks, and wives,
How many were going to St. Ives?
The last line turns out to be a trick question: only the speaker is going to St. Ives;
everyone else is presumably heading in the opposite direction. Suppose, however,
that you want to find out how many representatives of the assembled multitude—
kits, cats, sacks, and wives—were coming from St. Ives. Write a Java program to
calculate and display this result. Try to make your program follow the structure of
the problem so that anyone reading your program would understand what value it is
calculating.

/*
* File: OldNurseryRhyme.java
* ---------------------------
*  As I was going to St. Ives,
*  I met a man with seven wives,
*  Each wife had seven sacks,
*  Each sack had seven cats,
*  Each cat had seven kits:
*  Kits, cats, sacks, and wives,
*  How many were going to St. Ives?
*/

import acm.program.*;

public class OldNurseryRhyme extends ConsoleProgram {
public void run() {
int person = 1;
int man = 1;
int wifes = man * 7;
int sacks = wifes * 7;
int cats = sacks * 7;
int kits = cats * 7;
println("kits: " + kits);
println("cats: " + cats);
println("sacks: " + sacks);
println("wifes: " + wifes);
println("How many were going to st. Ives: " + person);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: