-2

This is C. I am a beginner, so sorry for the experts to whom this question may seem trivial. I am trying to round this float to the nearest integer, away from zero. I've also tried rintf based on some other posts on the internet, but it just won't work! I used printf to check the results, and they weren't rounded to the nearest integer.

//Approximate US grade level.
float index = 0.0588 * L - 0.296 * S - 15.8;

float roundf(float index);
  • 4
    Your question is missing critical parts: 1) how `roundf` is used/called 2) how you print the result and conclude. Post a [mcve]. – P.P Jul 22 '20 at 09:37
  • 3
    "but it just won't work! " lacks needed details. Post a [mcve]. " used printf to check the results, and they weren't rounded to the nearest integer." talks about the how, but code would be better. IAC, sample data is needed too. – chux - Reinstate Monica Jul 22 '20 at 09:41

2 Answers2

1

Note that

float roundf(float index);

is a declaration of a function. It is not a call.

If you use float roundf(float index); as function call inside of index = float roundf(float index); you should get a compiler error, but maybe you are on an uncommon compiler. Thus it can be a reason that it "won't work" as expected.

A correct call would be index = round(index);.

I used printf to check the results, and they weren't rounded to the nearest integer.

Note that floating-point precision isn't the best one in case you want to represent integers with it. A float or double can't represent an even integer value fully accurate. It has only a narrowed and limited precision.

Related:

0

Functions in C take an input and return an output in this way: output = function(input);. There may be more than one input for some functions, of course, but the principle is that.

For your case, try index = roundf(index); if you want the result to overwrite the non-rounded value.