C#隐式转换和显示转换举例--C#基础

时间:2023-03-09 07:44:59
C#隐式转换和显示转换举例--C#基础

高精度的数据类型转换为低精度的数据类型是显示转换,低精度的转换为高精度的是隐式转换。

温馨提示:不能说强制类型转换是从低精度到高精度。

int a=666;
float b=(float)a;

由a到b的转换是低精度到高精度的转换,为隐式转换,但是也加了强制转换(float),当然不加也是对的。

1、隐式转换示例:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace 表达式
{
class Program
{
static void Main(string[] args)
{
int x = ;
float y;
y = x;
Console.WriteLine(y);
Console.ReadKey();
}
}
}
//输出结果为:3
//c#中的变量如果需要输出就必须初始化,否则不能运行,不输出的可不初始化

2、显示转换示例:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace 表达式
{
class Program
{
static void Main(string[] args)
{
int x;
float y=1.2f;
x = (int)y;//高精度到低精度 需要强制类型转换
Console.WriteLine(x);
Console.ReadKey();
//C#中小数默认为double类型,所以float x=1.2;系统会提示不能将double=隐式转换为float类型,需要加上f后缀创建此类型
}
}
}