C#操作数字

1.静态类Math

 

 

 Math里的方法舍入是用的比较多的吧,然后三角函数,学过数学的人基本对这个都很清楚的。

2.BigInteger

BigInteger结构体是.NetFramework4.0新增的特殊值类型,它位于System.Numerics.dll的System.Numerics命名空间中。它可以表示任意大的整数而不会丢失精度。

                System.Numerics.BigInteger twentyfive = 25;
                Console.WriteLine(twentyfive);
                System.Numerics.BigInteger googol = System.Numerics.BigInteger.Pow(10, 100);//10的100次方
                Console.WriteLine(googol.ToString());

BigInteger重载了包括去余数(%)在内的所有算术运算符,还重载了顺序比较运算符。

另一种创建Biginteger的方式是从字节进行创建。

                System.Security.Cryptography.RandomNumberGenerator ran = System.Security.Cryptography.RandomNumberGenerator.Create();
                byte[] bytes = new byte[32];
                ran.GetBytes(bytes);
                var bigNumber = new System.Numerics.BigInteger(bytes);
                Console.WriteLine(bigNumber);

3.Cmoplex

Cmoplex结构体也是.NetFramework4.0新增的特殊值类型,它表示实部和虚部均为double类型的负数。

1                 var c1 = new System.Numerics.Complex(2, 3.5);
2                 Console.WriteLine(c1.Real);//实部
3                 Console.WriteLine(c1.Imaginary);//虚部
4                 Console.WriteLine(c1.Phase);//复数的相位
5                 Console.WriteLine(c1.Magnitude);//复数的量值
6                 Console.WriteLine(System.Numerics.Complex.Asin(c1));

其实这个值类型,对数学好的人理解是比较容易的,而且用的话花样也会很多。

4.Random

Random类能够生成类型为byte、integer、或double的伪随机数序列。

使用Random之前需要将其序列化,并可以传递一个可选的种子参数来初始化随机数序列。使用相同的种子(在相同的CLR版本下)一定会产生相同序列的数字。这个特性在重现过程中非常有用:

1  Random r1 = new Random(1);
2  Random r2 = new Random(1);
3  Console.WriteLine(r1.Next(100) + "," + r1.Next(100));
4  Console.WriteLine(r2.Next(100) + "," + r2.Next(100));

若不需要重现性,那么创建Random时无需提供种子,此时将用当前系统时间来生成种子。

由于系统时钟只有有限的粒度,因此两个创建时间非常接近(一般在10毫秒之内的)Random实例会产生相同值的序列。常用的方法是每当需要一个随机数时才序列化一个Random对象,而不是重用一个对象。声明单例的静态Random实例是一个不错的模式,但是在多线程环境下可能出现问题,因此Random对象并非线程安全的。

如果对随机数有加密要求的话可以使用 System.Security.Cryptography.RandomNumberGenerator。Random的随机数加密效果并不好。

1  System.Security.Cryptography.RandomNumberGenerator rand = System.Security.Cryptography.RandomNumberGenerator.Create();
2  byte[] bytes2 = new byte[4];
3  rand.GetBytes(bytes2);
4 ar o = BitConverter.ToInt32(bytes2,0);
5 Console.WriteLine(o);

总结

其实在System.Nuerics命名空间下很多都是能够操作数字的结构体,上述有两种就是在这个命名空间下的结构体。而一些静态类也能够实现对数字的操作,就如博客中说的两种,可能用的比较多的是Math。

 

posted @ 2020-04-25 15:10  飞天猪皮怪  阅读(361)  评论(0编辑  收藏  举报