簡體   English   中英

如何使用整數變量的長度作為for循環的終止條件

[英]How to use the length of an integer variable as the termination condition in a for loop

我有一個for循環,例如:

for (int indexCount = 2, thirdNumber.ToString().Length!=1000; indexCount++)

我希望當thirdNumber有1000位數字時終止循環。 我怎樣才能做到這一點?

不可能有1000位整數。 最大int值是2,147,483,647,只有10位數字。 據我所知,沒有內置的數據類型可以表示具有1000位數字甚至100位數字的數字。

編輯: BigInteger可以容納任意數量的數字(感謝Bradley Uffner )。 您需要添加對System.Numerics程序集的引用。 如果使用/正在使用該類型作為數據類型,則您對thirdNumber.ToString()!=1000原始比較將是有效的檢查,以查看其是否不是1000位數字。

您也可以采用基於數字的方法,將要檢查的BigInteger與最小的千位數進行比較,該數字是1,后跟999個零。 我不確定哪種方法使用這種大小的數字會更快,盡管我懷疑兩個BigInteger之間的比較。

class Program
{
    static void Main(string[] args)
    {
        BigInteger minThousandDigits = BigInteger.Parse(new string('9', 999)) + 1;
        BigInteger thousandMoreDigits = BigInteger.Parse(new string('5', 1000));
        BigInteger notAThousandDigits = BigInteger.Parse(new string('9', 999));

        //Displays false
        Console.WriteLine($"Is the first number less than a thousand digits? {thousandMoreDigits < minThousandDigits}");

        //Displays true
        Console.WriteLine($"Is the second number less than a thousand digits? {notAThousandDigits < minThousandDigits}");

        Console.ReadLine();

    }
}

使用do循環:

    int indexCount = 2;
    do 
    {
        // Whatever
        indexCount++;
    } while (thirdNumber.ToString().Length != 1000);

請注意,在以上示例中,循環將至少執行一次。 您可以通過使用break語句來避免這種情況:

    int indexCount = 2;
    do 
    {
        if (thirdNumber.ToString().Length == 1000) break;
        // Whatever
        indexCount++;
    } while (true);

以上假設長度最終將等於1000,否則您將遇到無限循環。

暫無
暫無

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

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