Codecademy C++ 练习题
CODE CHALLENGE: C++ FUNCTIONS
Introduction
1. Write a function introduction() with no return value that has:
std::stringparameter namedfirst_name.std::stringparameter namedlast_name.
The function should print the last_name, followed by a comma, a space, first_name another space, and finally last_name again.
For example, introduction("James", "Bond"); should print the following:
1 | Bond, James Bond |
Answer :
1 |
|
Average
1. Write a function average() that takes:
- A
doubleparameter namednum1. - A
doubleparameter namednum2.
The function should return a double that is the average of the arguments passed in.
Answer :
1 |
|
Tenth Power
1. Write a function named tenth_power() that has:
- An
intparameter namednum.
The function should return num raised to the 10th power.
Answer :
1 |
|
First Three Multiples
1. Write a function named first_three_multiples() that has:
- An
intparameter namednum.
The function should return an std::vector of the first three multiples of num in ascending order.
For example, first_three_multiples(7) should return a vector with 7, 14, and 21.
Answer :
1 |
|
Water Plant
1. Define a function needs_water() that accepts:
- An
intnumber ofdayssince the previous watering. - A
boolvalueis_succulent. (A value oftruewould indicate that the plant is a succulent.)
Inside the function, you’ll need some conditional logic:
- If
is_succulentisfalseanddaysis greater than3, return"Time to water the plant.". - If
is_succulentistrueanddaysis12or less, return"Don't water the plant!". - If
is_succulentistrueanddaysis greater than or equal to13, return"Go ahead and give the plant a little water.". - Otherwise, return
"Don't water the plant!".
Note: Don’t print the strings; return them from the function.
Answer :
1 |
|
Palindrome
1. Define a function is_palindrome() that takes:
- An
std::stringparametertext.
The function should return:
trueiftextis a palindrome.falseiftextis not a palindrome.
(A palindrome is any text that has the same characters backwards as it does forwards. For example, “hannah” and “racecar” are palindromes, while “menu” and “ardvark” are not.)
We will not test for edge cases such as capitalization or spaces.
Answer :
1 |
|
至此关于函数篇的六个小练习题完结。