#include <iostream> using namespace std; float Clamp( float a ) { float v = (a<0) ? 0 : (a<1) ? a : 1; return v; } int main () { cout<< -3 << "\t" << Clamp(-3) <<endl; cout<< 0.5f << "\t" << Clamp(0.5f) <<endl; cout<< 3 << "\t" << Clamp(3) <<endl; }
Output
-3 0 0.5 0.5 3 1
You can modify function to take interval , or use it as preprocessor directive.