您的位置:首页 > 编程语言 > C语言/C++

C语言运算中类型转换

2013-06-22 18:13 134 查看
int main(void)
{
unsigned int a = 6;
signed int b = -20;
signed int c = 6;

printf("%d\n",a+b);
(a+b) > a ? puts(">6") : puts("<=6");
(a+b) > c ? puts(">6") : puts("<=6");

return 0;
}


结果

-14
>6
>6


分析

看下面这段:

K & R A.6.5

Arithmetic Conversions(数值型间的转换)

First, if either operand is long double, the other is converted to long double.

Otherwise, if either operand is double, the other is converted to double.

Otherwise, if either operand is float, the other is converted to float.

Otherwise, the integral promotions are performed on both operands; then, if either operand is unsigned long int, the other is converted to unsigned long int.

Otherwise, if one operand is long int and the other is unsigned int, the effect depends on whether a long int can represent all values of an unsigned int; if so, the unsigned int operand is converted to long int; if not, both are converted to unsigned long
int.

Otherwise, if one operand is long int, the other is converted to long int.

Otherwise, if either operand is unsigned int, the other is converted to unsigned int.

Otherwise, both operands have type int.

[包含浮点型的运算]

如果任意一个操作数是long double, 那么另一个要转换为 long double

如果任意一个操作数是double, 那么另一个要转换为 double

如果任意一个操作数是float, 那么另一个要转换为 float

[2个非浮点型的运算]

如果任意一个操作数是unsigned long int, 那么另一个要转换为unsigned long int

如果一个操作数是long int, 另一个是unsigned int, 如果long int可以表示结果,那么unsigned int要转换为long int,否则两个都转换为unsigned long int

如果任意一个操作数是long int, 那么另一个要转换为long int

如果任意一个操作数是unsigned int, 那么另一个要转换为unsigned int

除此之外,两个操作数都应是int

C++ Floating-Point Constants(http://msdn.microsoft.com/en-us/library/ie/tfh6f0w2(v=vs.110).aspx)

Floating-point constants specify values that must have a fractional part. These values contain decimal points (.) and can contain exponents.

浮点型常量声明的值必须有小数部分。这些值包含小数点,也可以包含指数。

Floating-point constants default to type double. By using the suffixes
f or l (or F or L — the suffix is not case sensitive), the constant can be specified as
float or long double, respectively.

浮点型常量默认为double类型。通过使用后缀f或F,浮点型常量被声明为float类型,使用l或L后缀浮点型常量被声明为long
double
类型。

扩展

整型常量默认为int型(如果大小足够),使用l或L后缀浮点型常量被声明为long
类型,使用lu或LU后缀浮点型常量被声明为unsigned
long
类型。

使用ll或LL后缀浮点型常量被声明为long
long
类型,使用llu或LLU后缀浮点型常量被声明为unsigned
long long
类型。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: