C Language-type casting

Source: Internet
Author: User
Tags type casting

Conditions for casting:

1. When the declared type does not satisfy the variable of the character value, the type of the declaration needs to be converted so that the variable can be stored.

For example: The maximum value for short storage is 32767, but when the desired value is greater than 32767, the short type does not conform and the short type needs to be converted. Short marsold = 61600; the time is wrong.

2, loss of precision, when divided by a 1.0 and divided by 1 is different. May cause differences in values. Integer type divided by integer can only get integer type, before the character value is rounded before the value. A=int/int, even if a is a float but gets the value after rounding. You can get the accuracy calculation by turning int into float.

So you have to master the cast.

To convert a variable from one type to another, the target type should be placed in parentheses in front of the variable, which is called coercion type conversion.

Double sum = 0. 0;

int x = 1; int y = 2;

sum = (double)(x + y)/ 2-(x + y)/ (double)(x * x + y * y);

Implicit type conversions: when compiling in the presence of different types of value operations, the compiler handles the design and, according to certain rules, converts the type of one of the operands to the type of the other operand

1, the rule is in accordance with the high precision of the conversion of low precision to high precision. For example, a double, a long double, converts a double to a long double. An int and a float, int is converted to float.

2, otherwise, if the number of the type of two operands 都是带符号或无符号 , the lower-level operand is converted to another operand type. From left to right low to high (unsigned and signed levels): Char,short,int,long,long long

3, the judgment is converted into unsigned, to see the level of the type behind the symbol. For example long and a unsign int convert int to sign long.

C Language-type casting

Related Article

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.