【问题标题】:need some assistance with a perfect number exercise in C#在 C# 中进行完美的数字练习需要一些帮助
【发布时间】:2014-06-18 21:04:40
【问题描述】:

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

"如果一个整数的因数包括 一(但不是数字本身),求和。例如,6 是 一个完美的数字,因为 6 = 1 + 2 + 3。编写方法 Perfect that 确定参数值是否为完美数。用这个 确定并显示所有完美数字的应用程序中的方法 介于 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);
        }


    }
}
}
}

【问题讨论】:

  • for (int i = value; i == value; i++)?它有效吗?巫术!

标签: c# math perfect-numbers


【解决方案1】:

您调用了两次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);
        }
    }
}

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

【讨论】:

    【解决方案2】:

    您调用了两次IsItPerfect(i),其中包含Console.WriteLine()。您需要在if 之前删除IsItPerfect(i)。我还建议从您的方法中完全删除 UI - 这是不好的做法。

    【讨论】:

    • 什么是用户界面?用户界面?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多