1
#include <stdio.h>

int arredonda (double x)
{
    int arredondado;
    if (x - (int)x >= 0.5)
        arredondado = (int)x + 1;
    else
        arredondado = (int)x;
    return arredondado;
}

int main()
{
    double num;
    scanf("%f", &num);
    printf("%d", arredonda(num));
    return 0;
}

This is a function that rounds a number to upper or to lower depending of the decimal part. The problem is that it keeps returning 0 with all values.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
eduds
  • 11
  • 1
  • 1
    Does [how-to-round-floating-point-numbers-to-the-nearest-integer-in-c](https://stackoverflow.com/questions/2570934/how-to-round-floating-point-numbers-to-the-nearest-integer-in-c) helps you? – Hook Mar 29 '21 at 21:11
  • the posted code does not cleanly compile! Here is the compiler message: *untitled2.c:16:13: warning: format ‘%f’ expects argument of type ‘float *’, but argument 2 has type ‘double *’ [-Wformat=]* – user3629249 Mar 30 '21 at 23:44

1 Answers1

2

%lf must be used to input a double.

Make sure to enable your compiler's warnings!

a.c: In function ‘main’:
a.c:16:13: warning: format ‘%f’ expects argument of type ‘float *’, but argument 2 has type ‘double *’ [-Wformat=]
     scanf("%f", &num);
            ~^   ~~~~
            %lf

I use -Wall -Wextra -pedantic with gcc and clang.


As for the rounding itself, there is a better solution: round from math.h.

ikegami
  • 367,544
  • 15
  • 269
  • 518