0
float index = 0.0588 * L - 0.296 * S - 15.8;
int i = index;
printf("%i",i);
  1. //index equal 11.706415

  2. //when I convert the index to int the int will equal 11 "I want it to be 12"

2 Answers2

1

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
ikegami
  • 367,544
  • 15
  • 269
  • 518
0

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));
}
Allan Wind
  • 23,068
  • 5
  • 28
  • 38
  • Re "*Op didn't want a long they wanted an int.*" your comment doesn't make any sense. You're literally replying to me saying you can assign to a `long` to an `int` without cast (after you incorrectly claimed one was necessary), meaning they get an `int` as they wanted. I'm guessing you misread what I said??? Anyway, removed comments like I said I would, and I'll delete this one too. – ikegami Oct 12 '22 at 19:58
  • You suggested changing %d to %ld which means you are printing a long. To minimally change my code to use `roundl(index)` to print an int you need a cast. You could also assign it to a variable but that is not what my code currently does (and there is no win over using `roundf())`. I am very much open to feedback. If the point is to print the value, and it probably is, then your answer is superior anyways. – Allan Wind Oct 12 '22 at 20:34