C # type conversion tutorial,

Source: Internet
Author: User

C # type conversion tutorial,
C # type conversion

Sometimes it is really necessary to put different types of values together for calculation, such as: 3.5 + 8 what should we do at this time? There are two situations:

Automatic type conversion:

For two different types of data operations, the low-precision type is automatically converted to a higher-precision type.

Taking 3.5 + 8 as an example, it is clear that the precision of the number 8 is low (int), while that of the number 3.5 is high (double). Therefore, 8 is automatically converted to the double type, that is, convert to 3.5 + 8.0 for calculation, and the result is 11.5.

See this example:DoubleD = 2; the accuracy of 2 is obviously lower than the precision of the variable d, SO 2 will be automatically converted to 2.0 and then assigned to d.

Let's look at this example again:IntI = 3.0; the accuracy of variable I is less than 3.0, but because I has been declared as an int type variable, the value of the variable can be changed, butTypeIt cannot be changed, so this command willError.

Forced type conversion:

Cannot be automatically converted to the required type. You can use forced type conversion. For example, the preceding example can be completed as follows:

int i=(int)3.0;

The (int) before the number indicates that the destination type of the conversion is int, and 3.0 is forcibly converted to 3.

Note that,If the double type is forcibly converted to the int type, the fractional part is lost.For example, if (int) 2.8, we get 2.


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.