Allocation of operation in C

Asked

Viewed 255 times

3

I don’t understand why in doing this operation, even though I’ve already declared r as float, if you do not place the cast whether to assign 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.
}
  • 'Cause you’re splitting by 3 and not by 3.0... Do r = 8*2/3.0;.

1 answer

2


You don’t need the cast, but you need to use a number indicating that you are a float somehow. Both the 8, as to the 2 as to the 3 are integer numbers, so when he does the calculations they will generate integer numbers, there is no cast implied just because it had a division that could potentially 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);
}

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

Need to put the decimal part in all? In this case does not need, but has case that may need because of precedence and associativity. If you’re working with float use literals that are already float.

  • I understand, I must make explicit in the calculation at least one number. Thank you!

  • In the most important number, it is not enough in one, it can be in one, it depends on the location. Instead of the literal could use the cast, but it’s ugly.

Browser other questions tagged

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