簡體   English   中英

C#轉換為雙精度返回無窮大

[英]C# converting to double returns infinity

我有一個方法:

public void StoreNumberInSmallestType(ValueType number)
{
    if (numberTypes == null)
        numberTypes = new List<Type>() { typeof(sbyte), typeof(short), typeof(int), typeof(long), typeof(float), typeof(double) };

    foreach (Type t in numberTypes)
    {
        try
        {
            var converter = TypeDescriptor.GetConverter(t);
            value = converter.ConvertTo(number, t);

            Type = value.GetType();

            return;
        }

        catch (OverflowException) { }
    }
}

該方法位於類中,其中變量value定義為dynamic

當這樣使用時:

StoreNumberInSmallestType(Math.Pow(200, 100));

value最終是Infinity 如果我逐步執行此過程,我發現number的值不是Infinity ,而是用科學計數法表示的結果。 每當number被轉換並存儲在value時,就會發生不好的事情。 有人知道為什么number擁有正確的價值,而value卻沒有嗎?

編輯:

這是完整的代碼示例:

主要:

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Class1 c1 = new Class1();
            c1.StoreNumberInSmallestType(Math.Pow(200, 100));
        }
    }
}

類:

namespace ConsoleApplication1
{
    public class Class1
    {
        List<Type> numberTypes;
        dynamic value;
        public Type Type { get; set; }

        public void StoreNumberInSmallestType(ValueType number)
        {
            if (numberTypes == null)
                numberTypes = new List<Type>() { typeof(sbyte), typeof(short), typeof(int), typeof(long), typeof(float), typeof(double) };

            foreach (Type t in numberTypes)
            {
                try
                {
                    var converter = TypeDescriptor.GetConverter(t);
                    value = converter.ConvertTo(number, t);

                    Type = value.GetType();

                    return;
                }

                catch (OverflowException) { }
            }
        }
    }
}

當您使用最大值為3.40282347E+38的單一類型對數字進行轉換時,會發生這種情況,並且1.2676506002282294E+230的值為1.2676506002282294E+230因此您超出了單一值類型。 一旦您將其設置為Double類型,它將獲得1.2676506002282294E+230的價值。

從上面的鏈接:

如果浮點運算的結果的大小對於目標格式而言太大,則該運算的結果為PositiveInfinity或NegativeInfinity,適合於結果的符號。

對於double轉換,您不會得到無窮大,對於float轉換,您將不會無窮大。
在那里,您將獲得Infinity且沒有異常,然后在進行兩次轉換之前,代碼將返回。

溢出條件導致無限。 您可以使用以下任一方法進行檢查:

浮點轉換導致您超出數據類型的限制。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM