【发布时间】:2017-12-11 20:07:33
【问题描述】:
您能帮我做以下练习吗? (这不是家庭作业,只是我正在使用的书中的一个练习。)
“如果整数的因数(包括一个(但不包括数字本身))总和为该数,则称该整数为完美数。例如,6 是一个完美数,因为 6 = 1 + 2 + 3。编写判断参数值是否为完美数的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 并显示它是否完美(真或假)[这不是练习所要求的,但这是朝着正确方向迈出的一步(练习表明它应该只显示完美的数字)]。
无论如何,奇怪的是它在数字 24 处显示为真,这不是一个完美的数字....http://en.wikipedia.org/wiki/Perfect_numbers#Examples
为什么 24 不同?
非常感谢
【问题讨论】:
-
你有什么特别的错误吗?你得到了什么结果?
-
@MyCodeSucks 我想这更像是一个逻辑问题,而不是代码问题
-
@DanielAbouChleih:如果是这样,那么Code Review 的问题就更多了。
-
@user2723261:啊。看,这就是帮助解决问题所需的信息。编辑您的帖子以显示您获得的内容与您应该获得的内容。很有帮助。
-
为什么会有三票?这不是一个真正的问题,只是一个代码剪贴板。 “这个问题显示了研究工作;它有用且清晰”
标签: c# math perfect-numbers