常量与类型转换学习

类型转换是C#基础中很重要的一个知识点,特把遇到过的整理出来,供大家一起学习。

using System;

namespace lesson01{

	class MainClass{

		public static void Main (string[] args)
		{
	
			//常量——const  
			//数据类型  常量名  = 值(固定了,无法修改)注:常量不可二次赋值。
			const double PAI = 3.14;
			Console.WriteLine ("PAI={0}",PAI);
			Console.ReadLine ();

			//隐式类型转换(自动类型转换)
			//原类型小于目标类型(小转大)
			//byte < short < int < long
			int a = 3;
			float b = 4.5f;
			short c = 5;
			b = a;
			a = c;
			Console.WriteLine ("a={0},b={1}",a, b);
			Console.ReadLine ();

			//显式类型转换(强制类型转换)
			//原类型大于目标类型(大转小)
			//1、使用类型进行转换
			int i = 5;
			float j = 15.5f;
			i= (int)j;
			Console.WriteLine ("i={0}",i);
			Console.ReadLine ();

			//2、使用“Convert.To数据类型”进行转换
			int x = 6;
			float y = 9.1f;
			x = Convert.ToInt32(y);             //Int32—int,Int16—short,Int64—long
			int r = 4;
			float t= Convert.ToSingle(r);       //转float时,用ToSingle
			double z =Convert.ToDouble(r);      //转double
			Console.WriteLine ("x={0},t={1},z={2}",x,t,z);
			Console.ReadLine ();

			//3、使用类型的解析方法”数据类型.Parse”进行转换
			string str = "123";
			int v = int.Parse (str);
			string s = "5.6";
			float ss = float.Parse(s);
			Console.WriteLine ("v={0},vv={1}",v, ss);
			Console.ReadLine ();

			//从浮点类型的字符串转换到int需要两步
			int aa = (int)double.Parse("35.1");
			int bb = (int)Convert.ToDouble("35.1");
			Console.WriteLine ("aa={0},bb={1}",aa, bb);
			Console.ReadLine ();
		}

	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值