简体   繁体   中英

Largest data type to store numbers

I am making a scientific calculator in C# Winform application. In that I am using double to store the answers retrieved from the calculation of function e^x. But datatype double is having some limit if it exceeds then it show the overflow related error. So can you tell me what is the largest data type to store numbers in C#.

Example: 100!

double is the largest floating point precision data type in C#. You have BigInteger , but not a BigFloat or BigDouble .

There is however in the Base Class Library on CodePlex an implementation of BigRational , which are in fact two BigInteger s:

From there website:

BigRational builds on the BigInteger introduced in .NET Framework 4 to create an arbitrary-precision rational number type. A rational number is a ratio between two integers, and in this implementation BigIntegers are used for the numerator and denominator.

You should consider using System.Numerics.BigInteger data type. It represents an arbitrarily large signed integer. They have virtually no limit at all unlike you might have observed for other number data types available in .NET framework. You can read more about it here .

To use this structure you need to refer System.Numerics.dll in your project and then include below namespace at the top of the code file:

using System.Numerics;

You can go through this post on how to add reference to an assembly in case you get stuck somewhere.

Below is the sample code showing how to parse a very large number string and convert it into BigInteger :

var aVeryVeryHugeNumber = System.Numerics.BigInteger.Parse("31415926535897932384626433832795");

If you try to parse such a string representing a huge number, then it will result in System.OverflowException even with ulong.Parse data type. It fails with below error message:

Value was either too large or too small for a UInt64.

static void Main(string[] args)
    {
        Console.WriteLine("Geef een getal in?");
        double getal1 = Convert.ToDouble(Console.ReadLine());
        Console.WriteLine("Geef een tweede getal in?");
        double getal2 = Convert.ToDouble(Console.ReadLine());
        Console.WriteLine("Geef een derde getal in?");
        double getal3 = Convert.ToDouble(Console.ReadLine());

        if (getal1 > getal2 && getal1  > getal3)
        {
            Console.WriteLine(getal1 + "is het grootste getal");

        }
        if (getal2 > getal1 && getal2 > getal3) 
        {
            Console.WriteLine(getal2 + "is het grootste getal");
        }
        if( getal3 > getal2 && getal3 > getal1 )
        {
            Console.WriteLine(getal3 + "is het grootste getal");
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM