Someone in the group asked:
DoubleTempf= 20 / 230; Tempf= ??
Someone answered: 0.086956521739130434782608695652174 is calculated by a calculator.
But in. net, the result is 0.0.
But why? In fact, it is not surprising that in. net, the integer division is defined as follows:
- Integer Division:
Int operator/(int x, int y); uint operator/(uint X, uint y); long operator/(long X, long y); ulong operator/(ulong X, ulong y );
If the value of the right operand is zeroSystem. dividebyzeroexception
.
Division rounds the result to zero, and the absolute value of the result is the maximum possible integer that is smaller than the absolute value of the quotient of the two operands. When the two operand symbols are the same, the result is zero or positive. When the two operand symbols are the opposite, the result is zero or negative.
If the left operand is MinInt
OrLong
Value, and the right operand is-1
. Whether the operation is inChecked
Still inUnchecked
Occurs in context, which always triggersSystem. overflowexception
.
Therefore, the result of 20/230 should be 0, 0 assigned to a double type value, and it becomes 0.0.
In fact, our company's interview questions have a question like this:
Double Expectedvalue = 1 / 2 ; If (Expectedvalue > 0 ) {Expectedvalue = Expectedvalue + 0.5 ;} Console. writeline (expectedvalue );
ask what the final output is. I believe you can get the correct answer after my explanation above.