-1

I need to know a simple question, how is float sum = 1.1f + 1.2f; different from float sum = (float)(1.1+ 1.2); It is a C# code btw.

Thanks in advance

1 Answers1

0

The difference between the two exps is that in the first expression, the operands are explicitly cast to float using the f suffix. While the second expression, the operands are implicitly cast to double (the default type for floating-point literals in C#), and then explicitly cast to float using the (float) cast operator.

So, both expressions are equivalent and will produce the same result. However, the first expression is generally considered more readable, as it explicitly indicates that the operands are float values.

What is the problem you're trying to solve ?

Lorenzo Bassetti
  • 795
  • 10
  • 15
  • they both gave little different answers though, 2.3000002 is the answer to first expression, and the second one gives 2.3 – Moaz Haroon Jan 02 '23 at 13:37
  • This answer is incorrect on several accounts: `f` suffix doesn't do any casting, it denotes a float _literal_. The second expressions performs an operation with 2 `double` operands and then performs a narrowing cast from `double`→`float`. – knittl Jan 02 '23 at 16:01