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

JHTP练习题及课题_第六章_深入理解方法 (附加一些感慨)

2016-07-06 17:51 621 查看
“书读百遍,其义自见。”

最初,看题目看半天才看懂,看完题目不知何处着手;现在,看一遍题目,基本上心里已经有了一个解决方案的框架。

“天下无难事,只怕有心人”,每个人都有权利不断成长,关键在于你愿不愿意!

简单的事重复做、做好了,复杂的事情拆分成简单的事情,照样重复做、也能做好!


Exercises

6.7What is thevalue ofxafter
each of the following statements is executed?

a)x =Math.abs(7.5);
7.5

b)x =Math.floor(7.5);
7

c)x =Math.abs(0.0);
0

d)x =Math.ceil(0.0);
0

e)x =Math.abs(-6.4);
6.4

f)x =Math.ceil(-6.4);
-6

g)x =Math.ceil(-Math.abs(-8+
Math.floor(-5.5))); -14

6.8(ParkingCharges)A
parking garage charges a $2.00 minimum fee to park for up tothree

hours. The garage chargesan additional $0.50 per hour for each houror part
thereofin excess ofthree

hours. The maximum chargefor any given 24-hour period is $10.00. Assume that no car parks for

longer than 24 hours at atime. Write an application that calculates and displays the parking charges

for each customer whoparked in the garage yesterday. You should enter the hours parked for each

customer. The programshould display the charge for the current customer and should calculate and

display the running totalof yesterday’s receipts. It should use the methodcalculateChargesto
determine

the charge for eachcustomer.

6.9(RoundingNumbers)Math.floorcan
be used to round values to the nearest integer—e.g.,

y = Math.floor(x +0.5);

will round the numberxto
thenearest integer and assign the result toy. Write anapplication that

readsdoublevalues
anduses the preceding statement to round each of the numbers to the nearest

integer. For each numberprocessed, display both the original number and the rounded number.

6.10(RoundingNumbers)To
round numbers to specific decimal places, use a statement like

y = Math.floor(x *10+0.5)
/10;

which roundsxto
the tenthsposition (i.e., the first position to the right of the decimal point), or

y = Math.floor(x *100+0.5)
/100;

which roundsxto
thehundredths position (i.e., the second position to the right of the decimal

point). Write anapplication that defines four methods for rounding a numberxin
variousways:

a)roundToInteger(number)

b)roundToTenths(number)

c)roundToHundredths(number)

d)roundToThousandths(number)

For each value read, yourprogram should display the original value, the number rounded to the

nearest integer, thenumber rounded to the nearest tenth, the number rounded to the nearesthundredth

and the number rounded tothe nearest thousandth.

6.11Answer eachof the following questions:

a) What does it mean tochoose numbers “at random”?

b) Why is thenextIntmethod
ofclassSecureRandomuseful for simulating games of

chance?

c) Why is it oftennecessary to scale or shift the values produced by aSecureRandomobject?

d) Why is computerizedsimulation of real-world situations a useful technique?

6.12Writestatements that assign random integers to the variablenin
thefollowing ranges:

a) 1≤n≤2.

b) 1≤n≤100.

c) 0≤n≤9.

d) 1000≤n≤1112.

e) –1≤n≤1.

f) –3≤n≤11.

6.13Writestatements that will display a random number from each
of the following sets:

a) 2, 4, 6, 8, 10.

b) 3, 5, 7, 9, 11.

c) 6, 10, 14, 18, 22.

6.14(Exponentiation)Write
a methodintegerPower(base, exponent)that returnsthe value of

baseexponent

For example,integerPower(3,4)calculates34(or3
* 3 * 3 * 3). Assume thatexponentis
a positive,

nonzero integer and thatbaseis
aninteger. Use afororwhilestatement
to control the calculation.

Do not use anyMathclassmethods.
Incorporate this method into an application that reads

integer values forbaseandexponentand
performsthe calculation with theintegerPowermethod.

6.15(HypotenuseCalculations)Define
a methodhypotenusethat calculates thehypotenuse of

a right triangle when thelengths of the other two sides are given. The method should take two arguments

of typedoubleand
returnthe hypotenuse as adouble. Incorporate this method into an

application that readsvalues forside1andside2and
performs the calculation with thehypotenuse

method. UseMathmethodspowandsqrtto
determinethe length of the hypotenuse for each of the

triangles in Fig. 6.15. [Note:ClassMathalso
providesmethodhypotto perform this calculation.]

6.16(Multiples)Write
a methodisMultiplethat determines, for apair of integers, whether the

second integer is amultiple of the first. The method should take two integer arguments and return

trueif the secondis a multiple of the first andfalseotherwise.
[Hint:Use theremainder operator.]

Incorporate this methodinto an application that inputs a series of pairs of integers (one pair at a

time) and determineswhether the second value in each pair is a multiple of the first.

6.17(Evenor Odd)Write
a methodisEventhat uses the remainderoperator (%)
to determine

whether an integer iseven. The method should take an integer argument and returntrueif
theinteger

is even andfalseotherwise.Incorporate
this method into an application that inputs a sequence

of integers (one at atime) and determines whether each is even or odd.

6.18(Displayinga Square of Asterisks)Write
a methodsquareOfAsterisksthat displaysa solid

square (the same number ofrows and columns) of asterisks whose side is specified in integer parameter

side. Forexample, ifsideis4,
the method should display

****

****

****

****

Incorporate this methodinto an application that reads an integer value forsidefrom
the userand

outputs the asteriskswith thesquareOfAsterisksmethod.

6.19(Displayinga Square of Any Character)Modify
the method createdin Exercise 6.18 to receive

a second parameter oftypecharcalledfillCharacter.
Form the square using thecharprovided

as an argument. Thus, ifsideis5andfillCharacteris#,
the method should display

#####

#####

#####

#####

#####

Use the followingstatement (in whichinputis
aScannerobject) to read a character from the user

at the keyboard:

charfill =input.next().charAt(0);

6.20(CircleArea)Write
an application that prompts the user for the radius of acircle and uses

a method calledcircleAreato
calculate the area of the circle.

6.21(SeparatingDigits)Write
methods that accomplish each of the following tasks:

a) Calculate the integerpart of the quotient when integerais
divided byintegerb.

b) Calculate the integerremainder when integerais
divided by integerb.

c) Use the methodsdeveloped in parts (a) and (b) to write a methoddisplayDigitsthat

receives an integerbetween1and99999and
displays it as a sequence of digits, separating

each pair of digits bytwo spaces. For example, the integer4562should
appearas

4 5 6 2

Incorporate the methodsinto an application that inputs an integer and callsdisplay-

Digitsby passingthe method the integer entered. Display the results.

6.22(TemperatureConversions)Implement
the following integer methods:

a) Methodcelsiusreturns
theCelsius equivalent of a Fahrenheit temperature, using the

calculation

celsius =5.0/9.0*(fahrenheit
-32);

b) Methodfahrenheitreturns
the Fahrenheit equivalent of a Celsius temperature,using

the calculation

fahrenheit =9.0/5.0*
celsius+32;

c) Use the methods fromparts (a) and (b) to write an application that enables the user either

to enter a Fahrenheittemperature and display the Celsius equivalent or to enter a

Celsius temperature anddisplay the Fahrenheit equivalent.

6.23(Findthe Minimum)Write
a methodminimum3that returns the smallestof three floatingpoint

numbers. Use theMath.minmethod
toimplementminimum3. Incorporate the method into an

application that readsthree values from the user, determines the smallest value and displays theresult.

6.24(PerfectNumbers)An
integer number is said to be aperfect numberif itsfactors, including

1 (but not the numberitself), sum to the number. For example, 6 is a perfect number, because 6 =

1 + 2 + 3. Write a methodisPerfectthat
determines whether parameternumberis a perfectnumber.

Use this method in anapplication that displays all the perfect numbers between 1 and 1000. Display

the factors of eachperfect number to confirm that the number is indeed perfect. Challenge thecomputing

power of your computer bytesting numbers much larger than 1000. Display the results.

6.25(PrimeNumbers)A
positive integer isprimeif it’sdivisible by only 1 and itself.
For example,

2, 3, 5 and 7 are prime,but 4, 6, 8 and 9 are not. The number 1, by definition, is not prime.

a) Write a method thatdetermines whether a number is prime.

b) Use this method in anapplication that determines and displays all the prime numbers

less than 10,000. Howmany numbers up to 10,000 do you have to test to ensure that

you’ve found all theprimes?

c) Initially, you mightthink thatn/2
is the upper limit for which you must test to see

whether a numbernis
prime, butyou need only go as high as the square root ofn. Rewrite

the program, and run itboth ways.

6.26(ReversingDigits)Write
a method that takes an integer value and returns thenumber with

its digits reversed. Forexample, given the number 7631, the method should return 1367. Incorporate

the method into anapplication that reads a value from the user and displays the result.

6.27(GreatestCommon Divisor)Thegreatest
common divisor(GCD)
of twointegers is the largest

integer that evenlydivides each of the two numbers. Write a methodgcdthat
returnsthe greatest

common divisor of twointegers. [Hint:You
might want to use Euclid’s algorithm. You can find

information about it aten.wikipedia.org/wiki/Euclidean_algorithm.]Incorporate
the method

into an application thatreads two values from the user and displays the result.

6.28Write amethodqualityPointsthat
inputs a student’s average and returns4if it’s 90–100,

3if 80–89,2if
70–79,1if 60–69 and0if
lower than60. Incorporate the method into an application

that reads a value fromthe user and displays the result.

Making a Difference241

6.29(CoinTossing)Write
an application that simulates coin tossing. Let theprogram toss a coin

each time the userchooses the “Toss Coin”
menu option. Count the number of times each side of

the coin appears. Displaythe results. The program should call a separate methodflipthat
takes no

arguments and returns avalue from aCoin enum(HEADSandTAILS).
[Note:If the program realistically

simulates coin tossing,each side of the coin should appear approximately half the time.]

6.30(Guessthe Number)Write
an application that plays “guess the number” as follows:Your

program chooses thenumber to be guessed by selecting a random integer in the range 1 to 1000.

The application displaysthe promptGuess a number between 1 and 1000.
The player inputs afirst

guess. If the player'sguess is incorrect, your program should displayToo high.
Try again.orToo

low. Try again.to help theplayer “zero in” on the correct answer. The program should
prompt the

user for the next guess.When the user enters the correct answer, displayCongratulations.
You

guessed the number!, and allowthe user to choose whether to play again. [Note:The
guessingtechnique

employed in this problemis similar to a binary search, which is discussed in Chapter 19,

Searching, Sorting andBig O.]

6.31(Guessthe Number Modification)Modify
the program ofExercise 6.30 to count the number

of guesses the playermakes. If the number is 10 or fewer, displayEither you know
thesecret

or you got lucky!If the playerguesses the number in 10 tries, displayAha!
You know thesecret!

If the player makes morethan 10 guesses, displayYou should be able to do better!Why
should it

take no more than 10guesses? Well, with each “good guess,” the player should be able to eliminate

half of the numbers, thenhalf of the remaining numbers, and so on.

6.32(DistanceBetween Points)Write
methoddistanceto calculate the distancebetween two

points (x1,y1)
and (x2,y2).
Allnumbers and return values should be of typedouble. Incorporate

this method into anapplication that enables the user to enter the coordinates of the points.

6.33(CrapsGame Modification)Modify
the craps program of Fig. 6.8 to allow wagering.Initialize

variablebankBalanceto
1000 dollars. Prompt the player to enter awager. Check thatwager

is less than or equal tobankBalance,
and if it’snot, have the user reenterwageruntil a validwager

is entered. Then, run onegame of craps. If the player wins, increasebankBalancebywagerand
display

the newbankBalance.
If theplayer loses, decreasebankBalancebywager,
display the newbank-

Balance, checkwhetherbankBalancehas
become zero and, if so, display the message"Sorry.You

busted!"As the gameprogresses, display various messages to create some “chatter,”
such as"Oh,

you're going for broke,huh?"or"Aw
c'mon, take a chance!"or"You'reup big. Now's the time

to cash in yourchips!". Implement the “chatter” as a separate method that randomlychooses
the

string to display.

6.34(Tableof Binary, Octal and Hexadecimal Numbers)Write
an applicationthat displays a

table of the binary,octal and hexadecimal equivalents of the decimal numbers in the range 1

through 256. If you aren’tfamiliar with these number systems, read online Appendix J first.

Making a Difference

As computer costsdecline, it becomes feasible for every student, regardless of economiccircumstance,

to have a computer anduse it in school. This creates exciting possibilities for improving the

educational experience ofall students worldwide, as suggested by the next five exercises. [Note:

Check out initiativessuch as the One Laptop Per Child Project (www.laptop.org).
Also,research

“green” laptops—what aresome key “going green” characteristics of these devices? Look into the

Electronic ProductEnvironmental Assessment Tool (www.epeat.net),
which can help youassess

the “greenness” ofdesktops, notebooks and monitors to help you decide which products topurchase.]

6.35(Computer-AssistedInstruction)The
use of computers in education is referred to ascomputer-

assisted instruction(CAI).
Write aprogram that will help an elementary school student learn

242Chapter 6 Methods: ADeeper Look

multiplication. Use aSecureRandomobject
to produce two positive one-digit integers. The program

should then prompt theuser with a question, such as

How much is 6 times 7?

The student then inputsthe answer. Next, the program checks the student’s answer. If it’s correct,

display the message"Verygood!"and
ask another multiplication question. If the answer is wrong,

display the message"No.Please try again."and
let the student try the same question repeatedly

until the student finallygets it right. A separate method should be used to generate each new question.

This method should becalled once when the application begins execution and each time the

user answers the questioncorrectly.

6.36(Computer-AssistedInstruction: Reducing Student Fatigue)One
problem in CAIenvironments

is student fatigue. Thiscan be reduced by varying the computer’s responses to hold the student’s

attention. Modify theprogram of Exercise 6.35 so that various comments are displayed for

each answer as follows:

Possible responses to acorrect answer:

Very good!

Excellent!

Nice work!

Keep up the good work!

Possible responses to anincorrect answer:

No. Please try again.

Wrong. Try once more.

Don't give up!

No. Keep trying.

Use random-numbergeneration to choose a number from 1 to 4 that will be used to select

one of the fourappropriate responses to each correct or incorrect answer. Use aswitchstatement
to

issue the responses.

6.37(Computer-AssistedInstruction: Monitoring Student Performance)Moresophisticated

computer-assistedinstruction systems monitor the student’s performance over a period of time.The

decision to begin a newtopic is often based on the student’s success with previous topics. Modify

the program of Exercise6.36 to count the number of correct and incorrect responses typed by the

student. After thestudent types 10 answers, your program should calculate the percentage that are

correct. If thepercentage is lower than 75%, display "Please ask yourteacher for
extra help.",

then reset the program soanother student can try it. If the percentage is 75% or higher, display

"Congratulations,you are ready to go to the next level!",
then reset theprogram so another

student can try it.

6.38(Computer-AssistedInstruction: Difficulty Levels)Exercises
6.35–6.37developed a computer-

assisted instructionprogram to help teach an elementary school student multiplication. Modify

the program to allow theuser to enter a difficulty level. At a difficulty level of 1, the program

should use onlysingle-digit numbers in the problems; at a difficulty level of 2, numbers aslarge as

two digits, and so on.

6.39(Computer-AssistedInstruction: Varying the Types of Problems)Modify
theprogram of

Exercise 6.38 to allowthe user to pick a type of arithmetic problem to study. An option of1means

addition problems only,2meanssubtraction
problems only,3means multiplicationproblems only,

4means divisionproblems
only and5means a random mixture of all
these types.


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: