Home  >  Article  >  Backend Development  >  C# Learning Diary 04---Integer Type of Data Type

C# Learning Diary 04---Integer Type of Data Type

黄舟
黄舟Original
2017-01-20 13:26:021261browse

        上一篇中我们初步的了解了一些数据类型,不全面,本着认真求实的精神,我再对数据类型梳理 一下。

值类型之整数类型:

C# Learning Diary 04---Integer Type of Data Type

  记得以前上C语言 课 的时候老师也曾让我们看过这样的表格要求记下来,当时也没好好看认为记这个没什么用,可当我运行下面的代码的时候就知道老师的良苦用心了:

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
  
namespace Example  
{  
    class Program  
    {  
        static void Main(string[] args)  
        {  
            short x = 32766;  
            x++;  
            Console.WriteLine(x);  
            x++;  
            Console.WriteLine(x);  
            Console.ReadKey();  
        }  
    }  
}

结果出人所料:

C# Learning Diary 04---Integer Type of Data Type

为毛是负的????这个时候就章现了取值范围的伟大之处了  3268他超出了Short取值范围了;

与此类似的经历有很多,记得有一次老师叫我们写一个程序录入一个人的电话号码,然后输出,同桌说  “很简单嘛,三下五除二就写好了, ”代码如下:

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
  
namespace Example  
{  
    class Program  
    {  
        static void Main(string[] args)  
        {  
            int x;  
            Console.WriteLine("姓名:");  
            String name = Console.ReadLine();  
            Console.WriteLine("电话号码: ");  
            x = int.Parse(Console.ReadLine());   //类型转换  
            Console.WriteLine("你的名字叫:" + name + "\t" + "你的电话是:{0}", x);  
        }  
    }  
}

结果不能运行,原因就是int的有效位只有 10位 电话号码有11位 超出范围了,可以用long型 替代。再对输入与输出篇补充一点 :    Console.WriteLine("你的名字叫:"+name)  中间的加号  +   表示的是连接2个字符串的意思,也就是合二为一的意思,当表达式中有一个String类型时 ,比如 

int i =9;
  String Str = ”HC666“
  Console.WriteLine(Str+i);

运行输出为:

    HC6669

    这是因为当表达式中有String类型与int类型时   编译器自动将int 型 转化为String类型(隐式转换)然后再连接起来。后面会学习隐式转换。

   本着学无止境的精神,对上一篇日记的探索我有了新的发现:  定义变量名称时 用汉字也可以,并且不出错。

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
  
namespace Example  
{  
    class Program  
    {  
        static void Main(string[] args)  
        {  
            String 姓名="HC666";  
            int 年龄=16;  
            double 身高=1.70;  
            Console.WriteLine("姓名:{0},年龄:{1},身高:{2}", 姓名, 年龄, 身高);  
  
        }  
    }  
}

    其 实C#是支持多国语言编写的,不仅是中文,用日文、韩文……也都可以,不过建议还是用英文吧!!正好练习英语。


以上就是C#学习日记04---数据类型 之 整数类型的内容,更多相关内容请关注PHP中文网(www.php.cn)!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn