Unexpected result

2

I want to divide two integers and result in 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));
}

But the code below, which I believe to be equivalent to the one 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 is this happening?

    
asked by anonymous 07.09.2018 / 21:10

2 answers

2

Actually in modern compilers and well configured nor compiles. The code declares two variables as int and then tells them to read as float . Then the result is wrong indeed. But it only gives the error because the compiler has missed something that should not work. I suggest changing the compiler or configuring it so as not to let this type of error pass. And change the formatter from scanf() to %d in the code. That's right.

#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);
}

See running on ideone . And in Coding Ground . Also put it in GitHub for future reference .

Another possibility is to declare the variables as float and then get 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);
}

See running on ideone . And in Coding Ground . Also put it on GitHub for future reference .

scanf() documentation.

    
07.09.2018 / 21:20
1

x and y was declared at first as int and then you read with scanf ("%f", &y) , using %f , which is for float. Or you change to float x and y , or change %f to %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();
}
    
07.09.2018 / 21:20