C#自学03—Convert类型转换

  1. 类型如果相兼容的两个变量,可以使用自动类型转化或者强制类型转换,但是,如果两个变量不兼容,比如说String和int或者String和Double类型,这个时候我们就需要一种名叫convert的转换工厂进行转换。

    注意:使用Convert进行强制类型转化也要满足一个条件;那就是面上要过得去。例如:string num = “123abc”;不能转换成int数值型

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _03类型转换
{
    class Program
    {
        static void Main(string[] args)
        {
            //显示类型转换、自动类型转换
            //int--double   double  ----int

            //string s = "123abc";
            将字符串转换成int或者double类型
            //double d = Convert.ToDouble(s);
            //int n = Convert.ToInt32(s);
            //Console.WriteLine(n);
            //Console.WriteLine(d);
            //Console.ReadKey();


            //让用户输入姓名 语文 数学 英语 三门课的成绩,
            //然后给用户显示:XX,你的总成绩为XX分,平均成绩为XX分。
            Console.WriteLine("请输入你的姓名");
            string name = Console.ReadLine();
            Console.WriteLine("请输入你的语文成绩");//接下来将字符串变成double或者int类型
            string strChinese = Console.ReadLine();
            Console.WriteLine("请输入你的数学成绩");
            string strMath = Console.ReadLine();
            Console.WriteLine("请输入你的英语成绩");
            string strEnglish = Console.ReadLine();


            double chinese = Convert.ToDouble(strChinese);
            double math = Convert.ToDouble(strMath);
            double english = Convert.ToDouble(strEnglish);

            double sumScore = chinese + math + english;
            double avg = (int)sumScore*1.0 / 3;
            Console.WriteLine("{0}你的总成绩是{1}平均成绩是{2:0.00}", name, sumScore, avg);
            Console.ReadKey();

            //55 77  88  557788
            //由于字符串去相加的话,最终会变成相连接,如果要拿字符串类型的变量参与计算
            //需要将字符串转换成int或者double类型
            //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
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值