Assignment of operation in C

3

I do not understand why doing this operation, even if you have already declared r as float , if you do not put the cast operator it assigns a int .

#include <stdio.h>

void main() {
    float r;
    r = (float) 8 * 2 / 3;
    printf("O resultado eh: %.2f", r); // Sem o cast r= 5.00 que é errado.
}
    
asked by anonymous 21.08.2018 / 19:43

1 answer

2

You do not need cast , but you must use a number that indicates that it is a float somehow. Both 8 and 2 and 3 are integers, so when he does the calculations they will generate integer numbers, there is no implicit cast just because it has a division that potentially could give a decimal part. If you want the decimal part then say this.

#include <stdio.h>

void main() {
    printf("O resultado eh: %.2f", 8.0 * 2.0 / 3.0);
}

See running on ideone . And no Coding Ground . Also I placed GitHub for future reference .

Do you need to put the decimal part in everyone? In this case you do not need to, but have case that you may need because of precedence and associativity. If you are working with float use literals that already float .

    
21.08.2018 / 19:49