0

(これは宿題ではなく、私が使用している本の演習です)

「整数は、1 (ただし、数値自体ではない) を含む要素の合計が完全数であると言われます。たとえば、6 = 1 + 2 + 3 であるため、6 は完全数です。書き込み方法 Perfectパラメーター値が完全数かどうかを判断します。このメソッドは、2 から 1000 までのすべての完全数を判断して表示するアプリで使用します。各完全数の約数を表示して、その数が本当に完全数であることを確認してください。」

問題は、完全数が 1 回ではなく 2 回表示されることです。なぜこれを行うのですか?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Perfect_Numbers2
{
class Program
{
static bool IsItPerfect(int value)
{
    int x = 0;

    bool IsPerfect = false;

    List<int> myList = new List<int>();

    for (int i = value; i == value; i++)
    {
        for (int j = 1; j < i; j++)
        {
            if (i % j == 0)  // if the remainder of i divided by j is zero, then j     is a factor of i
            {
                myList.Add(j); //add j to the list

            }

    }
        x = myList.Sum();
        // test if the sum of the factors equals the number itself (in which     case it is a perfect number)
        if (x == i)    
        {
            IsPerfect = true;

            foreach (int z in myList)
            {
                Console.Write("{0} ",z);

            }

            Console.WriteLine(".  {0} is a perfect number", i);
        }            

    }
    return IsPerfect;
}

static void Main(string[] args)
{
    bool IsItAPerfectNum = false;



    for (int i = 2; i < 1001; i++)
    {
        IsItAPerfectNum = IsItPerfect(i);

        if (IsItPerfect(i) == true)
        {

            Console.ReadKey(true);
        }


    }
}
}
}
4

2 に答える 2

9

2 回呼び出しIsItPerfectているため、そのメソッドのコードが 2 回評価されます。このメソッドは数値をコンソールに書き込むため、数値が 2 回表示されます。

次のようにコードを書き直すと、問題が解消され、同じロジックを 2 回実行するのを防ぐことができます。

static void Main(string[] args)
{
    for (int i = 2; i < 1001; i++)
    {
        bool IsItAPerfectNum = IsItPerfect(i);

        if (IsItAPerfectNum)
        {
            Console.WriteLine("{0} is a perfect number", i);
            Console.ReadKey(true);
        }
    }
}

そしてもちろん、メソッドConsole.WriteLineから対応するものを削除してくださいItIsPerfect

于 2013-08-30T19:35:31.227 に答える
4

IsItPerfect(i)2 回呼び出していますが、 Console.WriteLine(). IsItPerfect(i)の前のを削除する必要がありifます。メソッドから UI を完全に削除することもお勧めします。これは悪い習慣です。

于 2013-08-30T19:38:47.147 に答える