簡體   English   中英

在Armstrong No。中為List或Array分配值時遇到問題

[英]Facing issue while assigning values to List or Array in Armstrong No

class Program
{
    static void Main(string[] args)
    {
        int temp;
        int arm, j = 0;
        List<int> armstrongnos = new List<int>();
        for (int i = 1; i < 1000; i++)
        {
            arm= 0;
            temp = i;
            while (i > 0)
            {
                arm += (i % 10) * (i % 10) * (i % 10);
                i /= 10;
            }
            if (arm== temp)
            {
                armstrongnos.Add(temp);// OutOfMemory Exception occurs whether you use array or list.
            }
        }
        foreach (var item in armstrongnos)
        {
            Console.WriteLine(item);
        }
        Console.ReadLine();
    }
}

我正在嘗試將強制打印no.sb / w 1打印到1000.在上面的代碼中確認它是一個非常強的沒有。 我將這些值分配給數組或列表。 但是我在這兩種情況下都有outofMemory Exception。 無法理解為什么會出現這個問題。 請幫助解決問題。 我在本准則中做錯了什么。 請解釋。

您正在運行無限循環。 你的循環停止條件是i < 1000 ,但是i 總是小於1000因為你在循環中減少它,而while (i > 0) ,但i 總是大於0 無限運行,您的代碼最終會遇到OutOfMemory異常。

如果你想與變量值玩, 從來不與循環的做i的迭代器-用做temp

for (int i = 1; i < 1000; i++)
{
    arm = 0;
    temp = i;

    while(temp > 0)
    {
       arm += (temp % 10) * (temp % 10) * (temp % 10); 
       temp /= 10;
    }
    if (arm == i)
       armstrongnos.Add(i);
}
foreach (var item in armstrongnos)
    Console.WriteLine(item);

Console.ReadLine();

問題是你正在修改你的迭代變量。

for (int i = 1; i < 1000; i++)
{
    // ...
    while (i > 0)
    {
        // ...
        i /= 10;
    }
    // ...
}

我已經刪除了相關部分。 您總是將迭代變量i分配並重新分配。 因此它將無限期地運行並始終向您的列表添加一個數字,直到它溢出。

相應地改變tempi ,它應該工作:

temp = i;
while(temp > 0)
{
   arm += (temp % 10) * (temp % 10) * (temp % 10);
   temp /= 10;
}
if (arm == i)
{
    armstrongnos.Add(i);
}

暫無
暫無

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

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