【问题标题】:C# perfect numbers exerciseC#完美数字练习
【发布时间】: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


【解决方案1】:

你能帮我做以下练习吗?

是的。我不会告诉你你的错误在哪里,而是教你如何找到你的错误。更好的是,同样的技术会降低你首先导致错误的机会。

这里的关键是将问题分解成小部分,每个小部分都可以独立测试。你已经开始这样做了!您有两种方法:MainIsItPerfect您应该至少还有三个方法。你应该有的方法是:

  • IsDivisor -- 接受两个整数,如果第一个整数除以第二个整数,则返回 true。
  • GetAllDivisors -- 接受一个整数,返回所有除数的列表
  • Sum -- 接受一个整数列表,返回总和

您的方法IsPerfect 应该调用GetAllDivisorsSum 并将总和与原始数字进行比较,这就是它应该做的所有。您的方法GetAllDivisors 应该调用IsDivisor,依此类推。

你不能轻易找到错误,因为你的方法做得太多。如果您没有得到正确的结果并且您有四种方法而不是一种,那么您可以独立测试每个方法以确保它有效,或者如果无效则修复它。

【讨论】:

  • 我意识到这不是您回答的重点,但 Linq .Sum() 有什么问题?为什么建议 OP 自己实现?
  • @Rotem:因为这是作为练习的初学者。编写自己的简单辅助方法实现可以塑造性格,并鼓励您将这些辅助方法视为非神奇的代码片段,由真人设计、实现和发布。
  • 将你的代码分成更小的块让你更接近SSCCE(短、自包含、正确(可编译)、示例)代码。 SSCCE 不仅让您更容易调试,而且对受访者来说也更容易调试。很大一部分 SO 社区不愿意回答非 SSCCE 问题(特别提到缺乏 SSCCE 是一个密切的原因)。
【解决方案2】:

您的第一个 for 循环将只执行一次。

for (int i = value; i <= value; i++)

例如对于值 = 6

for (int i = 6; i <= 6; i++)

【讨论】:

    【解决方案3】:

    对您遇到的 24 问题的一些帮助:24 正在返回 true,因为您实际上是在检查它是否在每个附加因素上都是完美的。所以 24 在这里被翻转为 true:

    Factors of 24 | Total so far
        1                1
        2                3
        3                6
        4                10
        6                16
        8                24     <-- returns true
        12               36     <-- should be false, but flag is never reset
    

    【讨论】:

    • @user2723261 更新以解释您的 24 问题
    【解决方案4】:

    我刚刚完成了同样的练习,该练习来自 Deitel 先生的一本非常棒的书,名为 visual c# 2012。

    我开始解决的方法是,我从弄清楚如何计算数字的阶乘开始,然后慢慢地从那里开始。

    由于您正在阅读同一本书,我建议您不要使用该章节练习未涵盖的内容,例如您使用过的列表集合,因为这会使练习变得不必要地困难。并否定作者提出的学习方法。

    这是我的代码,希望能对你有所帮助。

    class Program
    {
    
        static  int factorTotal = 1;
    
        static void Main(string[] args)
        {
    
                int count = 1;
                while (count <= 10000)
                {
                    bool isPerfect = IsPerfectNumber(count);
    
                    if (isPerfect && (factorTotal >1))
                    {
                        Console.WriteLine("Is Perfect: {0}", factorTotal);
    
                    }              
    
                    factorTotal = 1;
                    count++;
                }               
    
    
        } // end main
    
        static bool IsPerfectNumber(int n)
        {
            int temp;
            int counter = 2;
    
            bool IsPerfect = false;
    
            while (counter <= (n - 1))
            {
                temp = n % counter;
                if (temp == 0)  // if true than factor found
                {
    
                    factorTotal = factorTotal + counter;
                }
    
                counter++;
            }
    
            if ((factorTotal) == n)
                IsPerfect = true;
    
            else
                IsPerfect = false;
    
            return IsPerfect;
        }
    
    }//end class
    

    【讨论】:

      【解决方案5】:

      在控制台应用程序的 Main 方法下复制并粘贴以下代码。 我在代码末尾解释了几件事...

      ================================================ =======================

      {
              Console.WriteLine("perfect numbers/n");
              Console.Write("Enter upper limit: ");
              int iUpperLimit = int.Parse(Console.ReadLine());
              string sNumbers = "";
              List<int> lstFactor = new List<int>();
      
              for(int i = 1;i<=iUpperLimit;i++)
              {
                  for(int k = 1;k<i;k++)
                  {
                      if (i % k == 0)
                      {
                          lstFactor.Add(k); //this collect all factors
                      }
                      if (k == i-1)
                      {
                          if (lstFactor.Sum() == i) //explain1
                          {
                              sNumbers += " " + i;
                              lstFactor.Clear(); //explain2
                              break;
                          }
                          else
                          {
                              lstFactor.Clear(); //explain2
                          }
                      }
                  }
              }
      
              Console.WriteLine("\nperfect numbers are: " + sNumbers);
              Console.ReadKey();
          }
      }
      

      ================================================ ========================= 请注意,i 是我们测试的数字,k 是它的因子。

      explain1 => 我们将收集到的所有因子相加并检查它们是否等于i(我们只需检查i 是否为完美数)

      explain2 => 我们必须先清除列表,然后才能检查下一个数字i 是否是一个完美数字,以便前一个数字的因子不会干扰当前数字的因子。

      【讨论】:

        【解决方案6】:
            int start=1;
            int end=50;
        
            for(int a=end ; a > start ;a--)
            {
                int b=1;
                int c=0;
                bool x=false;
        
                for(int i=1 ; i < a ;i++)
                {
                    b=a/i;
                        if(b*i==a)
                        {
                            c+=i;
                        }
                        if(c==a & i==a/2)
                        {
                            x=true;
                        }
                }
                if(x==true)
                Console.Write("{0} is : {1}",a,x);
            }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-06-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-08-27
          相关资源
          最近更新 更多