2017-05-01 97 views
-3

我一直在試圖將它實現爲for循環。我寫了一個這個程序的流程圖。該程序需要重複,直到n = 1。我包含了一個鏈接到我的流程圖。如果有人能夠幫助我,那就太棒了。我需要幫助實現一個for循環

enter image description here

using System; 
namespace collatzconjecture 
{ 
    class MainClass 
    { 
     public static void Main(string[] args) 
     { 
      int n = Convert.ToInt32(Console.ReadLine()); 
      if (n == 1) 
      { 
       Console.WriteLine("n = {0}", n); 


      } 
      else if (n % 2 == 0) 
      { 
       int a = n/2; 
       Console.WriteLine("n = {0}", a); 

      } 
      else 
      { 
       int b = 3 * n + 1; 
       Console.WriteLine("n = {0}", b); 

      } 
      Console.ReadKey(); 

     } 
    } 
} 
+1

你究竟在掙扎着什麼?你不能獲得比簡單的for循環更多的基礎。 –

+0

你的意思是你想繼續做n/2或3 * n + 1,直到n爲1?如果是這種情況,那麼你真的想要一個'while'循環,而不是'for'循環,或者像流程圖那樣使用遞歸。 – juharr

+1

流程圖不循環。 – Romoku

回答

0

什麼你真的想要的是一個while循環,一直持續到n爲1.

public static void Main(string[] args) 
{ 
    int n = Convert.ToInt32(Console.ReadLine()); 
    Console.WriteLine("n = {0}", n); 
    while(n != 1) 
    { 
     if (n % 2 == 0) 
     { 
      n = n/2; 
     } 
     else 
     { 
      n = 3 * n + 1; 
     } 

     Console.WriteLine("n = {0}", a); 
    } 

    Console.ReadKey(); 
} 
1

如果你必須使用for,把它簡單,因爲它是描述:

開始與用戶輸入
  • 突破上n == 1
  • 下一步是
    • 3 * n + 1n/2

    是這樣的:

    public static void Main(string[] args) { 
        for (int n = Convert.ToInt32(Console.ReadLine()); // start with user input 
         n > 1;          // safier choice then n != 1 
         n = n % 2 == 0 ? n/2 : 3 * n + 1)   // next step either n/2 or 3*n + 1 
        Console.WriteLine(n); 
    
        Console.ReadKey(); 
    } 
    

    但是,如果可以選擇的執行情況,我建議提取專用邏輯到發電機:

    private static IEnumerable<int> Collatz(int n) { 
        while (n > 1) { 
        yield return n; 
    
        n = n % 2 == 0 
         ? n/2 
         : 3 * n + 1; 
        } 
    
        yield return n; 
    } 
    

    和UI

    public static void Main(string[] args) { 
        int n = Convert.ToInt32(Console.ReadLine()); 
    
        Console.Write(string.Join(Environment.NewLine, Collatz(n))); 
    } 
    
  • +0

    此代碼不能編譯。 –

    +0

    @Richard Irons:對不起,但代碼提取編譯(應該添加'class','namespace'),即使'for'循環非常*不尋常*。 –

    +0

    哦,是的,我剛剛意識到你在那裏做什麼。哎喲。這是一些非常討厭的代碼。 –