Integer Division in. net

Source: Internet
Author: User
Tags integer division

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 MinIntOrLongValue, and the right operand is-1. Whether the operation is inCheckedStill inUncheckedOccurs 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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.