Why I keep getting the wrong floating point result in C#

Something that took me while to figure out.

1 double result = 1 / 3; //will return 0.
2 double resutt = 1 / 3.0; // will return 0.33333
3

source-cs-iconEver wonder why I'm getting 0 (in Line 1) while i have already assign it to double type? Here’s the explanation: Line 1 return 0 as a result because C# interprets numeric value as integer, and integer division is performed with truncation; hence, 0. Line 2 is interpreted as floating point calculation because of 3.0 (putting a decimal point for the calculation to be done in floating point).

0 comments:

Post a Comment