Generic Range Clamping

#include <iostream>
#include <iomanip>

// TODO: Define a function template 'clamp_value'
// It should take three arguments of type T: val, min, max
// It should return T
template <typename T>
T clamp_value(T val, T min, T max) {
    if (val < min) return min;
    if (val > max) return max;
    return val;
}

int main() {
    int N;
    if (!(std::cin >> N)) return 0;

    for (int i = 0; i < N; ++i) {
        char type_code;
        std::cin >> type_code;

        if (type_code == 'i') {
            int val, min, max;
            std::cin >> val >> min >> max;
            // TODO: Call clamp_value for int
            std::cout << "Result: " << clamp_value(val, min, max) << std::endl;
        } else if (type_code == 'f') {
            float val, min, max;
            std::cin >> val >> min >> max;
            // TODO: Call clamp_value for float
            // TODO: Ensure output is formatted with 1 decimal place (std::fixed, std::setprecision)
            std::cout << "Result: " << std::fixed << std::setprecision(1) << clamp_value(val, min, max) << std::endl;
        }
    }
    return 0;
}

Solving Approach

 

 

 

 

 

Upvote
Downvote
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