Codecademy C++ 练习题
CODE CHALLENGE: C++ FUNCTIONS
Introduction
1. Write a function introduction()
with no return value that has:
std::string
parameter namedfirst_name
.std::string
parameter 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
double
parameter namednum1
. - A
double
parameter 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
int
parameter 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
int
parameter 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
int
number ofdays
since the previous watering. - A
bool
valueis_succulent
. (A value oftrue
would indicate that the plant is a succulent.)
Inside the function, you’ll need some conditional logic:
- If
is_succulent
isfalse
anddays
is greater than3
, return"Time to water the plant."
. - If
is_succulent
istrue
anddays
is12
or less, return"Don't water the plant!"
. - If
is_succulent
istrue
anddays
is 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::string
parametertext
.
The function should return:
true
iftext
is a palindrome.false
iftext
is 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 |
|
至此关于函数篇的六个小练习题完结。