Codementor Events

Assertions And Assumptions

Published May 26, 2021

When working with unknown Float Values and converting them to Integers. How can we determine an unknown Float value in a Condition to round it's converted Integer up to the nearest whole number.

By type casting we can succesfully convert a Float to an Integer but we cannot round those numbers without knowing the value of the Float.

What we have to do is use an Assertion on the Integer in the Conditional Statement then Assume the Floats value by adding 1/2 or .5 to its unknown value to reach it's mathmatical Assumed threshold whole number to conditionally compare it with its Asserted Integer Whole Number to know what the floats threshold value is and get our desired condition.

float fv = 5.463; // We do not know this value
int iv; 
iv=fv; // We do the type cast conversion
if(iv+1 >= fv+.5) {//We assert the Int to assume the float  
std::cout << iv << endl; //Leave the Int as non rounded 
} else { //Or
std::cout << iv++ << endl; //Increment the Int by 1 rounding it 
} 
//  

These mathmatics are rarely taught in Computer Science today, however they were used back in my day. And I have hundreds of mathmatics tricks to share with you here.
Thank You.

Discover and read more posts from robin deatherage
get started