在C#中需要一些完美数字练习的帮助

use*_*261 0 c# math perfect-numbers

(这不是作业,只是我正在使用的书中的练习)

"一个整数被认为是一个完美的数字,如果它的因素,包括一个(但不是数字本身),总和到数字.例如,6是一个完美的数字,因为6 = 1 + 2 + 3.写方法完美确定参数值是否为完美数字.在确定并显示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;

    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);
        }


    }
}
}
}
Run Code Online (Sandbox Code Playgroud)

Dan*_*ann 9

你正在调用IsItPerfect两次,这导致它两次评估该方法中的代码.该方法将数字写入控制台,因此它会显示两次数字.

您可以按如下方式重写代码,这将消除问题并阻止您执行两次相同的逻辑:

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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

当然,Console.WriteLine从您的ItIsPerfect方法中删除相应的.