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

 

Chapter 05 Methods
Review questions
-------------------------------------------------------------------------------
1. Explain in your own words the difference between a method and a program.
Answer:
    lies in who or what makes use of it
-------------------------------------------------------------------------------
2. Define the following terms as they apply to methods: call, argument, return.
Answer:
    call: to apply a mehtod
    aruments: pass the paramter to a method
    return: return a result from a method   
-------------------------------------------------------------------------------
3. What is the difference between passing information to a method by using
arguments and reading input data using methods like readInt? When would each
action be appropriate?
Answer:
    Input and output refer to communication between a program and its user.
Arguments and results represetn communication between a method and its caller.
-------------------------------------------------------------------------------
4. How do you specify the result of a method in Java?
Answer:
    return expression;
-------------------------------------------------------------------------------
5. Can there be more than one return statement in the body of a method?
Answer:
    yes. for example:
    private double min(double x, double y)
    {
        if (x < y)
            return x;
        else
            return y;
    }
-------------------------------------------------------------------------------
6. How do you indicate that you want to apply a method to another object?
Answer:
    reciever.name(arguments);
-------------------------------------------------------------------------------
7. Why has it been unnecessary to specify receivers in the programs presented in
the earlier chapters?
Answer:
    for those methods have defined in their superclass   
-------------------------------------------------------------------------------
8. Why was it unnecessary to include a break statement at the end of each case
clause in the monthName method presented in the chapter?
Answer:
    return statements automatically exit from the entire method
-------------------------------------------------------------------------------
9. What is a predicate method?
Answer:
    return values of type boolean
-------------------------------------------------------------------------------
10. How do you tell whether two strings contain the same characters?
Answer:
    private boolean haveSameCharacter(String s1, String s2)
    {
        for (int i = 0; i < s1.length(); i++)
            for (int j=0; j                 if (s1[i] == s2[j])
                    return true;

        return false;
    }
-------------------------------------------------------------------------------
11. What is the relationship between arguments and formal parameters?
Answer:
    copy
-------------------------------------------------------------------------------
12. Variables declared within a method are said to be local variables. What is
the significance of the word local in this context?
Answer:
    the variable scope
-------------------------------------------------------------------------------
13. What does the term return address mean?
Answer:
    the point at which execution should continue
-------------------------------------------------------------------------------
14. What is a brute-force algorithm?
Answer:
    int gcd(int x, int y)
    {
        int guess = Math.min(x, y);
        while (x % guess != 0 || y % guess != 0)
            guess--;
        return guess;
    }   
-------------------------------------------------------------------------------
15. Use Euclid’s algorithm to compute the greatest common divisor of 7735 and
4185.  What values does the local variable r take on during the calculation?
Answer:
    3350
    835               
    10
    5
    0
-------------------------------------------------------------------------------
16. In the examples of Euclid’s algorithm to calculate gcd(x, y) that appear in
this chapter, x is always larger than y. Does this condition matter? What
happens if x is smaller than y?
Answer:
    doesn't matter
    if x < y, then r = x % y = x and x != 0, so x = y and y = r
    then y > x;
-------------------------------------------------------------------------------

Programming exercises

1. Write a program that displays the value of the mathematical constant

This constant φ is called the golden ratio. Classical mathematicians believed that this
number represented the most aesthetically pleasing ratio for the dimensions of a
rectangle, but it also turns up in computational mathematics.

 

 

/* * File: GoldenRatio.java * ----------------------- * This program dispalys the golden ratio. * fi = (1 + sqrt(5)) / 2; */ import acm.program.*; import java.lang.Math; public class GoldenRatio extends ConsoleProgram { public void run() { double fi = (1 + Math.sqrt(5)) / 2; println("golden ratio: fi = " + fi); } }

/* * File: Quadratic.java * --------------------- * This program caculates the two solutions of * quaratic equation. * x1 = (-b + sqrt(b^2-4a*c)) / 2*a; * x2 = (-b - sqrt(b^2-4a*c)) / 2*a; */ import acm.program.*; import java.lang.Math; public class Quadratic extends ConsoleProgram { public void run() { println("Enter coefficients for the quadratic equation:"); double a = readDouble("a: "); double b = readDouble("b: "); double c = readDouble("c: "); double x1 = (-b + Math.sqrt(Math.pow(b, 2) - 4 * a * c)) / (2 * a); double x2 = (-b - Math.sqrt(Math.pow(b, 2) - 4 * a * c)) / (2 * a); println("The first solution is " + x1); println("The second solution is " + x2); } }

 

/* * File: FibonacciSequencesFromF0ThroughF15.java * --------------------------------------------- * This program displays the value of Fibonacci sequence from F0 * through F15. */ import acm.program.*; public class FibonacciSequencesFromF0ThroughF15 extends ConsoleProgram { public void run() { for (int i = 0; i <= 15; i++) { println("F" + i + " = " + fibonacci(i)); } } /* return nth fibonacci number. */ private int fibonacci(int n) { int ret = 0; int first = 0; int last = 1; for (int i=1; i <= n; i++) { ret = first + last; first = last; last = ret; } return ret; } }

/* * File: RaiseIntToPower.java * -------------------------- * This program displays the talbe of values of 2^k * for all values of k from 0 to 10. */ import acm.program.*; public class RaiseIntToPower extends ConsoleProgram { public void run() { for (int k = 0; k <= MAX_NUM; k++) { int ret = raiseIntToPower(2, k); println("2^" + k + " = " + ret); } } /* return n^k */ private int raiseIntToPower(int n, int k) {// n = 2, k = 0 int ret = 1; for (int i=1; i<=k; i++) { ret *= n; // ret = ret * n; } return ret; } private static final int MAX_NUM = 10; }

/* * File: RaiseRealToPower.java * ---------------------------- * This program displays a table of values of * PI^k for all values of k from -4 to 4. */ import acm.program.*; public class RaiseRealToPower extends ConsoleProgram { private static final double PI = 3.1415926535; private static final int MIN_NUM = -4; private static final int MAX_NUM = 4; public void run() { for(int k = MIN_NUM; k <= MAX_NUM; k++) { println( PI + "^" + k + " = " + raiseRealToPower(PI, k)); } } private double raiseRealToPower(double base, int pow) { double ret = 1; if (pow < 0) { base = 1 / base; pow = -pow; } for (int k=1; k <= pow; k++) ret *= base; return ret; } }

6. Write a method nDigits(n) that returns the number of digits in the integer n, which
you may assume is positive. Design a main program to test your method. For hints
about how to write this program, you might want to look back at the DigitSum
program that was given in Figure 4-6.

/* * File: Digits.java * ------------------ * This program display the number of digits in the integer n. */ import acm.program.*; public class Digits extends ConsoleProgram { public void run() { int i = 12345; println("the bits of " + i + " is " + nDigits(i)); } private int nDigits(int n){ int cnt = 0; while (n > 0) { cnt++; n /= 10; } return cnt; } }

7. Write a predicate method isPerfectSquare(n) that returns true if the integer n is a
perfect square. Remember that the method Math.sqrt returns a double, which is
therefore only an approximation of the actual square root.

 

/* * File: PerfectSquare.java * ------------------------- * This program test the isPerfectSquare(n) * that returns true if the integer n is a * perfect square. */ import acm.program.*; import java.lang.Math; public class PerfectSquare extends ConsoleProgram { private static final int MIN_NUM = 1; private static final int MAX_NUM = 100000000; public void run() { int cnt = 0; for (int i = MIN_NUM; i <= MAX_NUM; i++) { if (isPerfectSquare(i)) { cnt++; println(cnt + ": " + (int)Math.sqrt(i) + ": " + i ); } } } private boolean isPerfectSquare(int n) { int sqrt = (int)Math.sqrt(n); return (sqrt*sqrt == n); } }

8. Write a predicate method askYesNoQuestion(str) that prints out the string str as
a question for the user and then waits for a response. If the user enters the string
"yes", the askYesNoQuestion method should return true; if the user enters "no",
the method should return false. If the user enters anything else, askYesNoQuestion
should remind the user that it is seeking a yes-or-no answer and then repeat the
question. For example, if the program includes the statement


if (askYesNoQuestion("Would you like instructions")) . . .


the interaction with the user might look like this:

/* * File: YesNoExample.java * ------------------------ * This program displays the yes or no. */ import acm.program.*; import java.lang.*; public class YesNoExample extends ConsoleProgram { public void run() { if (askYesNoQuestion("Would you like instructions? ")) { println("Yes, I would like instructions."); } else { println("No, I wouldn'g like instructions."); } } private boolean askYesNoQuestion(String str) { String answer = readLine(str); while ( !answer.equals("yes") && !answer.equals("no")) { println("Please answer yes or no."); answer = readLine(str); } return (answer.equals("yes")); } }

/* * File: PascalTriangle * ---------------------- * This program displays the first eight rows of Pascal's Triangle. */ import acm.graphics.*; import acm.program.*; public class PascalTriangle extends GraphicsProgram { private static final int MIN_NUM = 0; private static final int MAX_NUM = 8; private static final int UNIT_LENGTH = 30; public void run() { int MIDDLE= getHeight() * 2 / 3; for (int i = MIN_NUM; i < MAX_NUM; i++) { for (int j = MIN_NUM; j <= i; j++) { add(new GLabel(""+combinations(i, j)), MIDDLE + (2*j- i) * UNIT_LENGTH , (i+1)*UNIT_LENGTH); } } } /* * Returns the mathematical combinations function C(n, k), * which is the number of ways of selecting k objects * from a set of n distinct objects. */ private int combinations(int n, int k) { return factorial(n) / (factorial(k) * factorial(n - k)); } /* * Returns the factorial of n, which is defined as the * product of all integers from 1 up to n. */ private int factorial(int n) { int result = 1; for (int i = 1; i <= n; i++) { result *= i; } return result; } }

10. An integer greater than 1 is said to be prime if it has no divisors other than itself and
one. The number 17, for example, is prime, because it is divisible only by 1 and 17.
The number 91, however, is not prime because it is divisible by 7 and 13. Write a
predicate method isPrime(n) that returns true if the integer n is prime, and false
otherwise. As an initial strategy, implement isPrime using a brute-force algorithm
that simply tests every possible divisor. Once you have that version working, try to
come up with improvements to your algorithm that increase its efficiency without
sacrificing its correctness.

/* * File: Primers.java * ------------------ * This program tests an integer for its prime. * An integer greater than 1 is said to be prime * if it has no divisors other than itself and * one. The number 17, for example, is prime, because * it is divisible only by 1 and 17. */ import acm.program.*; import java.lang.Math; public class Primers extends ConsoleProgram { private static final int START_NUM = 2; private static final int END_NUM = 1000; public void run() { for (int i = START_NUM; i <= END_NUM; i++ ) { if (isPrime(i)) { println(i + " is primer."); } } } private boolean isPrime(int num) { if (num <= 1) return false; //for (int i= 2; i < num; i++) { for (int i=2; i <= (int)Math.sqrt(num); i++) { if (num % i == 0) return false; } return true; } }

 

11. Greek mathematicians took a special interest in numbers that are equal to the sum of
their proper divisors (a proper divisor of n is any divisor less than n itself). They
called such numbers perfect numbers. For example, 6 is a perfect number because
it is the sum of 1, 2, and 3, which are the integers less than 6 that divide evenly into
6. Similarly, 28 is a perfect number because it is the sum of 1, 2, 4, 7, and 14.
Write a predicate method isPerfect(n) that returns true if the integer n is perfect,
and false otherwise. Test your implementation by writing a main program that uses
the isPerfect method to check for perfect numbers in the range 1 to 9999 by testing
each number in turn. Whenever it identifies a perfect number, your program should
display that number on the screen. The first two lines of output should be 6 and 28.
Your program should find two other perfect numbers in that range as well.

/* * File: PerfectNumbers.java * ------------------------- * This program dispay the perfect numbers from 1 to 9999. */ import acm.program.*; public class PerfectNumbers extends ConsoleProgram { private static final int START_NUM = 1; private static final int END_NUM = 9999; public void run() { for (int i = 1; i <= END_NUM; i++) { if (isPerfect(i)) { print(i + " = "); int cnt = 0; for (int j=1; j < i; j++) { if (i%j == 0) { cnt++; } } int icnt = 0; for (int j=1; j < i; j++) { if (i%j == 0 ) { print( j + (++icnt == cnt ? "" : " + ")); } } println(""); } } } /* if a number is perfect number, return ture. * Otherwise, return false. */ private boolean isPerfect(int num) { int sum = 0; for (int i=1; i < num; i++) { if (num % i == 0) { sum += i; } } return (sum == num); } }

 

 

最后一题没有做出来。。。待续

 

你可能感兴趣的:(stanford,编程方法)