float index = 0.0588 * L - 0.296 * S - 15.8;
int i = index;
printf("%i",i);
//index equal 11.706415
//when I convert the index to int the int will equal 11 "I want it to be 12"
CodePudding user response:
When you cast a float
to an int
it will be truncated. You can use roundf()
then cast the return value to an int
:
#include <math.h>
#include <stdio.h>
int main(void) {
float index = 11.706415;
printf("truncated: %d\n"
"rounded: %d\n",
(int) index,
(int) roundf(index));
}
CodePudding user response:
Your existing code rounds toward zero, also known as integer truncation. You appear to what some form of round to nearest, but you didn't specify which.
In this particular case, you can use
printf( "%.0f", index );
By default, this rounds to nearest, half to even.
This rounds to nearest, half away from zero.
#include <math.h> // Also need to link math lib (e.g. using -lm)
int i = lroundf( index );
This rounds to nearest, half up.
int i = index 0.5;
input | round to nearest half to even |
round to nearest half away from zero |
round to nearest half up |
---|---|---|---|
-7.5 | -8 | -8 | -7 |
-6.5 | -6 | -7 | -6 |
6.5 | 6 | 7 | 7 |
7.5 | 8 | 8 | 8 |