C#类型转换

类型转换

隐式类型转换:
  我们要求等号两遍参与运算的操作数的类型必须一致,如果不一致,满足下列条件会发生
  自动类型转换,或者称之为隐式类型转换。
  1、两种类型兼容
  例如:int 和 double 兼容(都是数字类型)
  2、目标类型大于源类型
  例如:double > int 小的转大的

namespace _类型转化
{
    class Program
    {
        static void Main(string[] args)
        {
            int T_shirt = 35;
            int trousers = 120;
            int totalMoney = 3 * T_shirt + 2 * trousers;
            Console.WriteLine(totalMoney);

            double realMoney = totalMoney * 0.88;
            Console.WriteLine(realMoney);
            Console.ReadKey();

            //int--->double
            //double d = number;//自动类型转换 隐式类型转换   int--double

        }
    }
}


显示类型转换:
  1、两种类型相兼容 int--double
  2、大的转成小的 double----int
  语法:
  (待转换的类型)要转换的值;

namespace _类型转换
{
    class Program
    {
        static void Main(string[] args)
        {
            double d = 303.6;
            //语法:
            //(待转换的类型)要转换的值;
            //double---->int//强制类型转换  显示类型转换
            int n = (int)d;
            Console.WriteLine(n);
            Console.ReadKey();
        }
    }
}

对于表达式,如果一个操作数为double类型,则整个表达式可提升为double型。

namespace _类型转换
{
    class Program
    {
        static void Main(string[] args)
        {
            int n1 = 10;
            int n2 = 3;
            double d = n1*1.0 / n2;//将其中一个操作数提升为double类型
            Console.WriteLine("{0:0.0000}",d);//用占位符保留小数位数
            Console.ReadKey();
        }
    }
}
原文地址:https://www.cnblogs.com/ssmile/p/7650036.html