The ternary operator predicate ? expression1 : expression2 has three pieces: a p
ID: 668102 • Letter: T
Question
The ternary operator predicate ? expression1 : expression2 has three pieces: a predicate question, such as x 10 and two expressions, the first is evaluated if the predicate is true and the second if the predicate is false. They are useful to write functions that are defined by cases. (They are a light-weight form of the traditional if-then-else construct.)
Write a function to express the following: If a person buys up to 100 units the cost per unit is 5 dollars, for every additional unit beyond 100 the cost is 4 dollars. The function should return the total cost to buy x units. (Use the ternary operator with x = 100 as the condition.
Explanation / Answer
x <= 100 ? 5.0 * x : (5.0*100) + 4*(x-100) #")
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.