溫馨提示×

C# BigDecimal怎樣實現除法

c#
小樊
88
2024-07-13 23:50:27
欄目: 編程語言

在C#中,可以使用BigDecimal類來實現高精度的除法運算。以下是一個示例代碼:

using System;
using System.Numerics;

namespace BigDecimalExample
{
    class Program
    {
        static void Main(string[] args)
        {
            BigInteger numerator = BigInteger.Parse("1234567890123456789");
            BigInteger denominator = BigInteger.Parse("9876543210987654321");

            BigDecimal result = BigDecimal.Divide(new BigDecimal(numerator), new BigDecimal(denominator));

            Console.WriteLine("Result of division: " + result);
        }
    }

    public class BigDecimal
    {
        private BigInteger _value;

        public BigDecimal(BigInteger value)
        {
            _value = value;
        }

        public static BigDecimal Divide(BigDecimal dividend, BigDecimal divisor)
        {
            BigInteger result = BigInteger.DivRem(dividend._value, divisor._value, out _);

            return new BigDecimal(result);
        }

        public override string ToString()
        {
            return _value.ToString();
        }
    }
}

在上面的示例中,首先定義了一個BigDecimal類,其中包含一個BigInteger類型的值。然后在Main方法中,定義了兩個BigInteger類型的數值并將其轉換為BigDecimal類型。接著調用BigDecimal類中的Divide方法來進行除法運算,并最后輸出結果。

0