Unexpected result

Asked

Viewed 103 times

2

I wish to carry out the division of two integers and have as a result a floating point value.

The following code works normally:

#include <stdio.h>

float divInts(int x, int y)
{
    return((float)x/y);
}

void main()
{
    printf("%f",divInts(50,3));
}

However, the code below, which I believe is equivalent to the above, does not work as expected, returning the value 1.031615 when dividing 50/3, instead of 16.666667:

#include <stdio.h>

void divInts()
{
    int x;
    int y;
    float resultado;

    printf ("Entre o numerador 'x' :\n");
    scanf ("%f", &x);

    printf ("Entre o denominador 'y' :\n");
    scanf ("%f", &y);

    resultado = (float)x / y;

    printf("O resultado da divisao entre x e y, em formato ponto flutuante e : %f\n\n", resultado);
}

void main()
{
    divInts();
}

Why does this happen?

2 answers

2


Actually in modern and well-configured compilers it doesn’t even compile. The code declares two variables as int and then have them read as if they were float. Then the result really goes wrong. But it only gives the error because the compiler missed something that should not work. I suggest to change the compiler or configure it so as not to pass this type of error. And change in the code the formatter of scanf() for %d. That’s how it’s done.

#include <stdio.h>

int main() {
    int x;
    int y;
    printf ("Entre o numerador 'x' :\n");
    scanf ("%d", &x);
    printf ("Entre o denominador 'y' :\n");
    scanf ("%d", &y);
    printf("O resultado da divisao entre x e y, em formato ponto flutuante e : %f\n\n", (float)x / y);
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Another possibility is to declare variables as float and then take the value already in the complete type.

#include <stdio.h>

int main() {
    float x;
    float y;
    printf ("Entre o numerador 'x' :\n");
    scanf ("%f", &x);
    printf ("Entre o denominador 'y' :\n");
    scanf ("%f", &y);
    printf("O resultado da divisao entre x e y, em formato ponto flutuante e : %f\n\n", x / y);
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Documentation of scanf().

1

The x and the y was declared at the beginning as int and then you did the reading with scanf ("%f", &y), using the %f, which is for float. Or you change to float the x and y, or exchange the %f for %f:

#include <stdio.h>

void divInts()
{
    int x;
    int y;
    float resultado;
    printf ("Entre o numerador 'x' :\n");
    scanf ("%d", &x);
    printf ("Entre o denominador 'y' :\n");
    scanf ("%d", &y);
    resultado = (float) x / y;
    printf("O resultado da divisao entre x e y, em formato ponto flutuante e : %f\n\n", resultado);
}
main()
{
    divInts();
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.