#include // In many applications, a value must be restricted to // lie within a specified interval. // // For example, suppose that a value 'x' must be restricted // to the interval // // [-bound, bound]. // // If 'x' is greater than 'bound', replace it with 'bound'. // If 'x' is less than '-bound', replace it with '-bound'. // Otherwise, leave 'x' unchanged. // // This operation is often called "clipping" or "saturation." // Mathematically, we can define // // / -bound, if x < -bound, // | // clip(x) = < x, if -bound <= x <= bound, // | // \ bound, if x > bound. // // For example, if bound = 5: // // x = 8.2 -> clip(x) = 5 // x = 5.0 -> clip(x) = 5 // x = 3.7 -> clip(x) = 3.7 // x = 0.0 -> clip(x) = 0 // x = -2.4 -> clip(x) = -2.4 // x = -5.0 -> clip(x) = -5 // x = -9.1 -> clip(x) = -5 // // The graph of this function is: // // // bound | ________________ // | / // | / // |/ // - - - - - - - - - - + - - - - - - - - - - x // /|0 // / | // -bound ________________/ | // | // // // Notice the three portions of the graph: // // 1. For x < -bound, the output is constant at -bound. // // 2. For -bound <= x <= bound, the output equals x. // // 3. For x > bound, the output is constant at bound. // // Write a program that asks the user for 'x' and a // non-negative value 'bound' and then prints clip(x). // // If the user enters a negative value for 'bound', // immediately terminate the program by returning 0 // from main(). // Function declarations int main(); // Function definitions int main() { double x{}; std::cout << "Enter a number 'x': "; std::cin >> x; double bound{}; std::cout << "Enter a non-negative bound: "; std::cin >> bound; if ( bound < 0.0 ) { return 0; } // There are three possibilities corresponding to // the three portions of the graph. if ( x > bound ) { // 'x' is above the permitted interval, so clip // it to the upper bound. std::cout << "clip(x) = " << bound << std::endl; } else if ( x < -bound ) { // 'x' is below the permitted interval, so clip // it to the lower bound. std::cout << "clip(x) = " << -bound << std::endl; } else { // We now know that // // -bound <= x <= bound, // // so 'x' is already within the permitted interval. std::cout << "clip(x) = " << x << std::endl; } return 0; }