136. Generic Range Clamping

In embedded firmware, variables must often be restricted to safe operating ranges (e.g., limiting a PWM duty cycle to 0-255 or a servo angle to -45 to +45). Legacy code frequently uses unsafe preprocessor macros (e.g., #define CLAMP), which suffer from type-safety issues and double-evaluation bugs.

Your task is to implement a function template named clamp_value. It must accept three parameters of a generic type T: value, min_limit, and max_limit. It returns the value constrained within the range [min_limit, max_limit].

  • If value is less than min_limit, return min_limit.
  • If value is greater than max_limit, return max_limit.
  • Otherwise, return value.

The function must work correctly for both integers and floating-point types.

Program Flow:

  1. Read integer N (number of test cases).
  2. Loop N times:
  3. Read character type_code ('i' for int, 'f' for float).
  4. If type_code is 'i':
    • Read integers val, min, max.
    • Call clamp_value<int> with these arguments.
    • Print the result.
  5. If type_code is 'f':
    • Read floats val, min, max.
    • Call clamp_value<float> with these arguments.
    • Print the result with 1 decimal place of precision (e.g., 10.0).

Input Format:

  • First line: Integer N (number of test cases).
  • Next N lines: Character type_code, followed by three numbers (val, min, max).
  • Input is provided via standard input (stdin).

Output Format:

  • For each case, print: Result: <value>
  • Floating point numbers must be printed with 1 decimal place (e.g., 10.0, -5.0).
  • Each output must be on a new line.

Example: 

Example 1 (Mixed Types)

Input:

4
i 100 0 255
i 300 0 255
f 12.5 0.0 10.0
f -5.0 -10.0 0.0

Output:

Result: 100
Result: 255
Result: 10.0
Result: -5.0

Constraints:

  • N range: 1 to 20
  • val, min, max will be valid numeric types.
  • Assume min_limit <= max_limit is always true.
  • Must use template <typename T> syntax.
  • No macros allowed.

 

 

 

Loading...

Input

4 i 100 0 255 i 300 0 255 f 12.5 0.0 10.0 f -5.0 -10.0 0.0

Expected Output

Result: 100 Result: 255 Result: 10.0 Result: -5.0