Is this:
int i = 100 * 0.6;
less correct than this?
int i = 100 * (0.6F);
I apologize for such a simple question, but I haven't memorized all the rules for data type promotions and I'm not really sure how to even verify this.
It can make a difference. For example:
int i = (1 << 24) + 3;
printf("%d\n", (int)(i * 0.6)); // 10066331
printf("%d\n", (int)(i * 0.6f)); // 10066332
The reason is that the calculation for the first is done in double-precision, the latter in single-precision. Single-precision cannot represent all integers greater than 1 << 24
.
Another example (courtesy of @EricPostpischil in the comments below):
int i = 100;
printf("%d\n", (int)(i * 0.29)); // 28
printf("%d\n", (int)(i * 0.29f)); // 29
Here the reason is that the intermediate result in the double-precision case falls slightly below 29, and so is truncated down to 28.
So I would suggest allowing double-precision (i.e. omitting the f
/F
) (and then using round()
rather than relying on implicit truncation) unless you have a good reason to do otherwise.
The F
is not required in this particular case. All it does is specify the constant as being of type float
instead of type double
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With