温馨提示×

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