Reputation: 9019
Would you consider this to be a bug, or to be expected behaviour?
Consider the following
1 * (2/(1+2))
equals 0
1 * ((double)2/(1+2))
equals 0.6667
Upvotes: 0
Views: 71
Reputation: 174339
This is not a bug. Arithmetic operations where all operands are int
yield an int
as result.
This is also documented in the MSDN:
When you divide two integers, the result is always an integer. For example, the result of 7 / 3 is 2. To determine the remainder of 7 / 3, use the remainder operator (%). To obtain a quotient as a rational number or fraction, give the dividend or divisor type float or type double. You can do this implicitly by expressing the dividend or divisor as a decimal by putting a digit to the right of the decimal point
Upvotes: 3
Reputation: 5493
You should use double/float numbers if you wanna to have result in this format:
1 * (2.0/(1+2))
or
1 * (2f/(1+2))
or
1 * (2d/(1+2))
Upvotes: 1
Reputation: 10376
It is ok, since you have used ints in your expression. You can use double operands instead of cast:
1d * (2d/(1d+2d))
Here is link: http://msdn.microsoft.com/en-us/library/678hzkk9(v=vs.71).aspx
Upvotes: 1