黑马程序员--C语言里的类型转换学习笔记

Windows Phone 7手机开发Net培训期待与您交流!

实际编程中,经常遇到类型的相互转换问题,如一个int类型要转换成一个long类型。类型转换方法分为隐式类型转换和显式类型转换,也可以采用Convert的方法实现类型转换。

1 .隐式数值转换
数值转换是指在整数类型、实数类型和字符类型之间的转换。 sbyte 类型向 int 型转换是一种隐式数值类型转换,转换一般不会失败,也不会丢失数据。例如:
sbyte a = 100;
int b = a; 
可转换到的类型
可能有信息丢失
sbyte
short, int, long, float, double, decimal

 

byte
short, ushort, int, uint, long, ulong, float, double,  decimal

 

short
int, long, float, double, decimal

 

ushort
int, uint, long, ulong, float, double, decimal

 

int
long, float, double, decimal
float
uint
long, ulong, float, double, decimal
float
long
float, double, decimal
float double
ulong
float, double, decimal
float double
char
ushort, int, uint, long, ulong, float, double, decimal

 

float
double

 

 


2.显式类型转换
 

显式类型转换只有在某些情况下实现转换,规则复杂,需要用户正确指定要转 换的类型,又称强制类型转换。
1 .显式数值转换
int 类型向 byte 类型转换就是一种显式数值类型转换。例如:
int b = 100;
sbyte a =(byte)b;
sbyte 取值范围是 0 255 ,当 int b 显式转换为 sbyte 时不会丢失信息。
int b = 1000;
sbyte a =(byte)b;
则会丢失信息,这是显式数值转换过程要注意的。
 
可转换到的类型
sbyte
byte, ushort, uint, ulong, char
byte
sbyte ,char
short
sbyte, byte, ushort, uint, ulong, char
ushort
sbyte, byte, short, char
int
sbyte, byte, short, ushort, uint, ulong, char
uint
sbyte, byte, short, ushort, int, char
long
sbyte, byte, short, ushort, int, uint, ulong, char
ulong
sbyte, byte, short, ushort, int, uint, long, char
char
sbyte, byte, short
float
sbyte, byte, short, ushort, int, uint, long, ulong, char, decimal
double
sbyte, byte, short, ushort, int, uint, long, ulong, char, float, decimal
decimal
sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值