eduds
eduds

Reputation: 11

My function keeps returning 0 instead of the actual value

#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.

Upvotes: 1

Views: 205

Answers (1)

ikegami
ikegami

Reputation: 386676

%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.

Upvotes: 2

Related Questions