#include // A piecewise-defined function uses different formulas // for different values of its argument. // // Consider the following "tent" function: // // / 0, x <= -1, // | // | x + 1, -1 < x <= 0, // tent(x) = < // | 1 - x, 0 < x <= 1, // | // \ 0, 1 < x. // // Its graph looks like a tent: // // // | // 1 + // /|\ // / | \ // / | \ // / | \ // _________________/ | \_________________ // -1 0 1 // | // // // Notice that the function has four different portions: // // 1. If x <= -1, the value is 0. // // 2. If -1 < x <= 0, the value is x + 1. // // 3. If 0 < x <= 1, the value is 1 - x. // // 4. If x > 1, the value is 0. // // For example: // // x = -2.0 -> tent(x) = 0 // x = -1.0 -> tent(x) = 0 // x = -0.7 -> tent(x) = 0.3 // x = 0.0 -> tent(x) = 1 // x = 0.4 -> tent(x) = 0.6 // x = 1.0 -> tent(x) = 0 // x = 1.8 -> tent(x) = 0 // // Write a program that asks the user for a value of 'x' // and then evaluates and prints tent(x). // // A cascading conditional statement is particularly // useful for implementing a piecewise-defined function. // Function declarations int main(); // Function definitions int main() { double x{}; std::cout << "Enter a number 'x': "; std::cin >> x; if ( x <= -1.0 ) { // We know that // // x <= -1, // // so tent(x) = 0. std::cout << "tent(x) = " << 0.0 << std::endl; } else if ( x <= 0.0 ) { // The first condition was false, so we already // know that // // x > -1. // // Together with the current condition, we know // // -1 < x <= 0. // // Thus, tent(x) = x + 1. std::cout << "tent(x) = " << (x + 1.0) << std::endl; } else if ( x <= 1.0 ) { // The first two conditions were false, so we // already know that // // x > 0. // // Together with the current condition, we know // // 0 < x <= 1. // // Thus, tent(x) = 1 - x. std::cout << "tent(x) = " << (1.0 - x) << std::endl; } else { // All three conditions were false, so we know // // x > 1. // // Thus, tent(x) = 0. std::cout << "tent(x) = " << 0.0 << std::endl; } return 0; }