-2

I made a program that can get the largest integral of a float value:

#include <stdio.h>

float get_value(float a);

int main() {
    float num = 4.58;
    float new_val = get_value(num);
    printf("%f \n", new_val);
}

float get_value(float a) {
    int c = a;
    for (int i = 0; i < 99; i++) {
        a -= 0.01;
        if (a == c) {
            break;
        }
    }
    return a;
}

It didn't work in the way I wanted it to be, so I want a shorthand of it instead of making a function.

So is there a function that I can use for this?

luser droog
  • 18,988
  • 3
  • 53
  • 105
  • 2
    This doesn't work the way you think it should because [floating point math is weird](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Gereon Sep 05 '20 at 10:52
  • 1
    Okay, I guess that makes sense. @Gereon –  Sep 05 '20 at 11:01

2 Answers2

1

Use floor() if you want the lowest integer (closest to minus infinity) not exceeding the floating point value. Or use trunc() to get the smallest integer (closest to zero) not exceeding the magnitude of the fp value.

Also, note that .1 has a repeating representation in binary fp, so your function as written is always going to have problems. Just like 1/3 becomes .3333 in decimal.

luser droog
  • 18,988
  • 3
  • 53
  • 105
  • That's the function I need. The `floor()` gave me 4.00, which is the result I'm looking for, and `trunc()` gave me the same thing. –  Sep 05 '20 at 10:53
  • @IPlayGamesBro What do you want for negative values? – stark Sep 05 '20 at 12:23
  • I just need to get the smallest average of a float, then use it for other operations. @stark –  Sep 06 '20 at 09:29
1

You can use modf:

double integral, fractional;
double num = 4.58;
int result;

fractional = modf(num, &integral);
result = (int)integral;
David Ranieri
  • 39,972
  • 7
  • 52
  • 94