您的位置:首页 > 编程语言 > C#

c#中的整形类型

2016-06-27 10:39 555 查看
一、整型类型

C#中定义了8中整数类型:字节型(byte)、无符号字节型(ubyte)、短整型(short)、无符号短整型(ushort)、整型(int)、无 符号整型(uint)、长整型(long)、无符号长整型(ulong)。划分依据是该类型的变量在内存中所占的位数。

C#中每个整数类型都对应于.NET类库中定义的一个结构,这些结构在程序集System中定义。上述结构均提供两个基本属性:MinValue和MaxValue,分别表示类型的最小值和最大值。

数据类型说明取值范围对应于System程序集中的结构
sbyte有符号8位整数-128~127SByte
byte无符号8位整数0~255Byte
short有符号16位整数-32768~32767Int16
ushort无符号16位整数0~65535UInt16
int有符号32位整数-2147483648-2147483647Int32
uint无符号32位整数0~4294967295UInt32
long有符号64位整数-9223372036854775808~9223372036854775807Int64
ulong无符号64位整数0~18446744073709551615UInt64
整数取值范围代码:

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

namespace IntegerRange
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("整数类型的取值范围:");
// sbyte
Console.Write("SByte:\t");
Console.Write(SByte.MinValue);
Console.Write("~");
Console.WriteLine(SByte.MaxValue);

// byte
Console.Write("Byte:\t");
Console.Write(Byte.MinValue);
Console.Write("~");
Console.WriteLine(Byte.MaxValue);

// short
Console.Write("Int16:\t");
Console.Write(Int16.MinValue);
Console.Write("~");
Console.WriteLine(Int16.MaxValue);

// ushort
Console.Write("UInt16:\t");
Console.Write(UInt16.MinValue);
Console.Write("~");
Console.WriteLine(UInt16.MaxValue);

// int
Console.Write("Int32:\t");
Console.Write(Int32.MinValue);
Console.Write("~");
Console.WriteLine(Int32.MaxValue);

// uint
Console.Write("UInt32:\t");
Console.Write(UInt32.MinValue);
Console.Write("~");
Console.WriteLine(UInt32.MaxValue);

// long
Console.Write("Int64:\t");
Console.Write(Int64.MinValue);
Console.Write("~");
Console.WriteLine(Int64.MaxValue);

// ulong
Console.Write("UInt64:\t");
Console.Write(UInt64.MinValue);
Console.Write("~");
Console.WriteLine(UInt64.MaxValue);

Console.WriteLine();
}
}
}


执行结果:

整数类型的取值范围:
SByte:  -128~127
Byte:   0~255
Int16:  -32768~32767
UInt16: 0~65535
Int32:  -2147483648~2147483647
UInt32: 0~4294967295
Int64:  -9223372036854775808~9223372036854775807
UInt64: 0~18446744073709551615

请按任意键继续. . .


如果类型取值超出了取值范围,程序在运行时就会发生溢出。

Byte溢出代码:

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

namespace IntegrateOverflow
{
class Program
{
static void Main(string[] args)
{
byte b = 100;
b = (byte)(b + 200); // 溢出

Console.WriteLine(b);
}
}
}


执行结果:

44
请按任意键继续. . .


二、源代码

IntegerRange.rar

IntegrateOverflow.rar

感谢分享, 这个类型所占的数字范围 在其他编程语言里面似乎也是相似或者通用的
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: