簡體   English   中英

為什么返回 0? 它應該 output 18446744073709551615,應該適合

[英]Why is this returning 0? It should output 18446744073709551615, which should fit

此代碼返回 0,它應該返回 18446744073709551615,它應該適合 ulong? 當我將其設置為迭代 63 次(而不是 64 次)時,我得到 9223372036854775808,這是正確的。

public static ulong Total()
{
    ulong output = 1ul ; 
    for(var x = 0; x < 64; x++)
    {
        output *= 2;
    }
    return output;
}

您正在計算 2^64,它不是 18446744073709551615 而是 1844674407370955161 6 您可能會注意到,當您將 64 更改為 63 時,您得到的是 9223372036854775808 而不是 9223372036854775807。

您所做的計算超出了包含大值所需的ulong字節數的容量......

https://docs.microsoft.com/dotnet/csharp/language-reference/builtin-types/integral-numeric-types

例如,您需要使用小數:

public static decimal Total()
{
  decimal output = 1ul;
  for ( var x = 0; x < 64; x++ )
  {
    output *= 2;
  }
  return output;
}

這個 output 18446744073709551616

事實上,如果我們使用ulongchecked關鍵字添加到方法中:

public static ulong Total()
{
  ulong output = 1ul;
  for ( var x = 0; x < 64; x++ )
  {
    output = checked(output * 2);
  }
  return output;
}

我們得到一個溢出異常。

您還可以將System.Numerics.BigInteger用於非常大的整數。

https://docs.microsoft.com/dotnet/api/system.numerics.biginteger

暫無
暫無

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

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