⭐C# 常用数字类型在C#中,常用的数字类型包括整数类型和浮点数类型。每种类型都有其特定的用途和适用场景。下面列出了C#中最常用的数字类型及其特点:

🌟整数类型
●byte:○占用1个字节(8位),范围从0到255。○适用于存储较小的正整数。●short或Int16:○占用2个字节(16位),范围从-32,768到32,767。○适用于存储中等大小的整数。●int或Int32:○占用4个字节(32位),范围从-2,147,483,648到2,147,483,647。○最常用的整数类型,适用于大多数场景。●long或Int64:○占用8个字节(64位),范围从-9,223,372,036,854,775,808到9,223,372,036,854,775,807。○适用于需要更大范围的整数,如日期和时间戳。●uint或UInt32:○占用4个字节(32位),范围从0到4,294,967,295。○适用于存储较大的正整数。●ulong或UInt64:○占用8个字节(64位),范围从0到18,446,744,073,709,551,615。○适用于存储非常大的正整数。●sbyte或SByte:○占用1个字节(8位),范围从-128到127。○类似于byte,但支持负数。●nint和nuint:○这两个类型是平台相关的整数类型,nint代表有符号整数,nuint代表无符号整数。○它们在不同平台上可能占用不同的字节数(32位或64位)。🌟浮点数类型●float:○占用4个字节(32位),有效数字大约为7位。○适用于需要较高速度的科学计算,但精度较低。●double:○占用8个字节(64位),有效数字大约为15-16位。○适用于需要较高精度的科学计算。●decimal:○占用16个字节(128位),有效数字最多可达28-29位。○专门用于货币和财务计算,提供高精度。🌟特殊类型●BigInteger:○不是基本类型,而是System.Numerics命名空间中的结构体。○可以表示任意大小的整数,但性能不如固定大小的整数类型。🌟示例代码下面是一个简单的示例,演示如何使用这些数字类型:
using System;class Program{static void Main(){byte byteValue = 100;short shortValue = 5000;int intValue = 1_000_000;long longValue = 100_000_000_000L;float floatValue = 3.141592f;double doubleValue = 2.718281828459045;decimal decimalValue = 1.99m;Console.WriteLine($"Byte Value: {byteValue}");Console.WriteLine($"Short Value: {shortValue}");Console.WriteLine($"Int Value: {intValue}");Console.WriteLine($"Long Value: {longValue}");Console.WriteLine($"Float Value: {floatValue}");Console.WriteLine($"Double Value: {doubleValue}");Console.WriteLine($"Decimal Value: {decimalValue}");}}
using System;class Program{static void Main(){decimal price = 19.99m; // 使用'm'后缀指定decimal类型的数值decimal quantity = 5m;decimal total = price * quantity;Console.WriteLine($"Price: {price:C}");Console.WriteLine($"Quantity: {quantity:N0}");Console.WriteLine($"Total: {total:C}");}}
int maxInt = int.MaxValue;int overflowExample = maxInt + 1;Console.WriteLine("Overflow Example: " + overflowExample); // 输出: -2147483648
double numberWithDecimal = 3.14;int integerPart = (int)numberWithDecimal;Console.WriteLine("Integer Part: " + integerPart); // 输出: 3
int intNumber = 3;double doubleNumber = 0.1;double result = intNumber * doubleNumber;Console.WriteLine("Result: " + result); // 输出: 0.3
double a = 0.1;double b = 0.2;double sum = a + b;Console.WriteLine(sum);
float a = 0.1f; // 注意这里的'f'后缀,它告诉编译器这是一个float类型的字面量float b = 0.2f;float sum = a + b;Console.WriteLine("Sum: " + sum); // 输出可能不是预期的0.3Console.WriteLine("Sum as decimal: " + (decimal)sum); // 使用(decimal)强制转换查看更详细的数值
float result = 0.1f + 0.1f + 0.1f - 0.3f;Console.WriteLine("Result: " + result); // 可能输出一个非零的小数,如2.77555756156289E-08
