2013-08-30 41 views
0

(這不是功課,只是在我使用這本書的練習)需要一個完美的數字運動在C#中一些援助

「的整數被認爲是如果它的因素完全數,其中包括 一個(但不是數字本身),總和爲該數字。例如,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); 
     } 


    } 
} 
} 
} 
+1

'for(int i = value; i == value; i ++)'?它的工作原理?巫術! – vroomfondel

回答

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

和當然,從你的ItIsPerfect方法刪除相應的Console.WriteLine

+3

奧卡姆剃鬚刀的行動.. –

4

您打電話IsItPerfect(i)兩次,它包含一個Console.WriteLine()。您需要在if之前刪除IsItPerfect(i)。我還建議完全從您的方法中刪除UI - 它的不好的做法。

+1

什麼是UI?用戶界面? – user2723261