Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiplying an integer by a float literal - is the "F" required?

Tags:

c

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.

like image 893
Adam S Avatar asked Dec 18 '13 17:12

Adam S


2 Answers

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.

like image 82
Oliver Charlesworth Avatar answered Sep 19 '22 13:09

Oliver Charlesworth


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.

like image 28
ldav1s Avatar answered Sep 17 '22 13:09

ldav1s