类型转换(.NET基础 )

来源:互联网 发布:新浪微博淘宝卖家认证 编辑:程序博客网 时间:2024/06/05 18:18
类型转换(条件:类型兼容 double int )
小转大 、自动类型转换(隐式转换)
大转小 、强制类型转换(显示转换)
语法:
(待转换的类型)要转换的值
int i = (int)2.3;
如果两个类型的变量不兼容,比如string和int或者string和double,这是我们可以使用一个叫做Convert的转换工厂进行转换。
注意:使用Convert进行类型转换,也需要满足一个条件:面上必须要过得去
using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace 类型转换{    class Program    {        static void Main(string[] args)        {            //int n1 = 10;            //int n2 = 3;            //int---》double   小转大 、自动类型转换(隐式转换)            //double d = n1*1.0/n2;  //自动类型转换            //Console.WriteLine(d);            //Console.WriteLine("{0:0.00}",d); //保留小数点后两位            //double a = 562.2;            //double---》int 大转小 、强制类型转换(显示转换)            //语法:            //(待转换的类型)要转换的值            //int i = (int)a;            //Console.WriteLine(i);            //将string 转换成int或double,使用Convert进行转换            //string s = "123";            //double d = Convert.ToDouble(s);            //int i = Convert.ToInt32(s);            //Console.WriteLine(d);            //Console.WriteLine(i);            //练习:让用户输入姓名、语文、数学、英语三门成绩,然后给用户显示:某某,你的总成绩是多少分,平均成绩是多少分            Console.WriteLine("请输入您的姓名:");            string name = Console.ReadLine();            Console.WriteLine("请输入您的语文成绩:");            string strchinese = Console.ReadLine();            Console.WriteLine("请输入您的数学成绩:");            string strmath = Console.ReadLine();            Console.WriteLine("请输入您的英语成绩:");            string strenglish = Console.ReadLine();            //由于字符串去相加的话,最终会变成相连接,如果要拿字符串类型的变量参与计算            //需要将字符串转换成int或者double类型            //转换成double类型            double chinese = Convert.ToDouble(strchinese);            double math = Convert.ToDouble(strmath);            double english = Convert.ToDouble(strenglish);            Console.WriteLine("{0},你的总成绩是{1},平均成绩是{2}", name, chinese + math + english, (chinese + math + english) / 3);            //转换成int类型            //int chinese= Convert.ToInt32(strchinese);            //int math = Convert.ToInt32(strmath);            //int english = Convert.ToInt32(strenglish);                       //Console.WriteLine("{0},你的总成绩是{1},平均成绩是{2}", name, chinese + math + english, (chinese + math + english)/3);            Console.ReadKey();        }    }}

0 0