次の演習を手伝ってくれませんか?(これは宿題ではなく、私が使用している本の演習です。)
「整数は、1 (ただし、数値自体ではない) を含む要素の合計が完全数であると言われます。たとえば、6 = 1 + 2 + 3 であるため、6 は完全数です。書き込み方法 Perfectパラメータ値が完全数であるかどうかを判断します。このメソッドは、2 から 1000 までのすべての完全数を判断して表示するアプリで使用します。各完全数の約数を表示して、その数が本当に完全数であることを確認してください。
だからここに私がこれまでに得たものがあります:
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;
int counter = 0;
bool IsPerfect = false;
List<int> myList = new List<int>();
for (int i = value; i <= value; i++)
{
for (int j = 1; j < value; j++)
{
// if the remainder of i divided by j is zero, then j is a factor of i
if (i%j == 0) {
myList[counter] = j; //add j to the list
counter++;
}
for (int k = 0; k < counter; k++)
{
// add all the numbers in the list together, then
x = myList[k] + myList[k + 1];
}
// test if the sum of the factors equals the number itself (in which case it is a perfect number)
if (x == i) {
IsPerfect = true;
}
}
Console.WriteLine(i);
}
return IsPerfect;
}
static void Main(string[] args)
{
bool IsItAPerfectNum = false;
for (int i = 2; i < 1001; i++)
{
IsItAPerfectNum = IsItPerfect(i);
}
}
}
}
どのようにしますか?私のコードは修正可能ですか? どのように修正しますか?ありがとう!
行 myList[counter] = j; でエラーが発生しています。(インデックスが範囲外でした)それに加えて、本来のように完全な数が表示されていません....
編集 = いくつかの変更を加えました。
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;
int counter = 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();
if (x == i) // test if the sum of the factors equals the number itself (in which case it is a perfect number)
{
IsPerfect = true;
}
}
Console.WriteLine(i);
}
return IsPerfect;
}
static void Main(string[] args)
{
bool IsItAPerfectNum = false;
for (int i = 2; i < 1001; i++)
{
IsItAPerfectNum = IsItPerfect(i);
Console.WriteLine(IsItAPerfectNum);
Console.ReadKey(true);
}
}
}
}
これで、すべての数字を 1000 まで繰り返し表示し、それが完全かどうか (true または false) を表示します [これは演習で求められたものではありませんが、正しい方向への一歩です (演習では、表示する必要があると述べています)完全数のみ)]。
いずれにせよ、奇妙なのは、完全数ではない 24 番が true であるということです.... http://en.wikipedia.org/wiki/Perfect_numbers#Examples
なぜ24は違うのですか?
どうもありがとう