类型转换
一、隐式转换
- 将占⽤字节⼩的、取值范围⼩的、精度⼩的,转换为占⽤字节⼤的、取值范围⼤的、精度⾼的
- 不需要任何的修饰符,会⾃动转换
- int可转换为float和double,long也可转化为float和double,整数可转化为浮点数,且long类型取值范围小于float类型,不会出现数据错误。
//整型
//sbyte short int long
sbyte englishScore = 100;
//sbyte --> int
int myScore = englishScore;
//int --> long
long classScore = myScore;
//int --> float
float newScore = myScore;
//float --> double
double newClassScore = newScore;
二、显式转换
- 将占⽤字节⼤的、取值范围⼤的、精度⾼的转换为占⽤字节⼩的、取值范围⼩的、精度⼩的
- 需要强制转修饰符,会有精度的缺失,甚⾄数据的错误
- 转换情况:知道这个数字,在⼩的数据类型的取值范围内
- 举例:short 转换成 sbyte:0000 0000 0000 0110 --> 0000 0110
//强制转换
int damage = 1000000;
//int --> sbyte
sbyte health = (sbyte)damage;
float mathScore = 90.5f;
//float --> int
int myAllScore = (int)mathScore;
//会把⼩数点后⾯的内容全部舍去
- int和char之间的类型转换
int转为char和char转为int都是ASCII码值 - string与其他类型之间的转换方法:
1、System.Convert:
System.Convert.ToBoolean()
System.Convert.ToInt32()
System.Convert.ToSingle()
System.Convert.ToDouble()
System.Convert.ToChar()
2、 数据类型.Parse():
int.Parse()
bool.Parse()
float.Parse()
char.Parse()
3、其他类型转string:其他类型的变量.ToString();
输入与输出
一、输出
- Console.WriteLine();输出内容,并换⾏
- Console.Write();输出内容,不换⾏
二、输入:
- Console.Read();从屏幕读取⼀个字符,并返回该字符所对应的ascll码值
- Console.ReadLine();从屏幕读取⼀串字符,并返回该字符串