【问题标题】:Why won't my Pascal's Triangle java code work?为什么我的 Pascal 的三角形 java 代码不起作用?
【发布时间】:2017-05-02 00:32:58
【问题描述】:

我的问题最近被搁置了,所以我决定再问一次。

我的教授希望我们在 Java 上制作帕斯卡三角形。他为我们提供了一个完整的 Main 类,它应该可以工作,我们必须使用它。我们不必编辑 Main 类。 Main 类是正确的。它需要我们必须在代码中编写的方法。另外,我提供了正确的输出和 Pascal 类的模板,其中包含我应该填写的方法。

这里是主类:

 public class Main 
  {

  public static void main(String[] args) 
  {

    int n = args.length == 1 ? Integer.parseInt(args[0]) : 1;

    for (int i = 1; i <= n; ++i) 
    {
        int[] arr = Pascal.triangle(i);
        System.out.print((i < 10 ? " " : "") + i + ": ");
        for (int j : arr) 
        {
            System.out.print(j + " ");
        }
        System.out.println();
    }
 }
}

我的教授希望我们使用他的 Pascal 类模板,我们只需要在代码中编写三角形方法。这是我们必须为分配编写代码的唯一区域。

 public class Pascal 
 {
   public static int[] triangle(int n) 
   {
     //My code goes here
     return new int[]{0};
   }
 }

输出应该是这样的:

 1: 1 
 2: 1 1 
 3: 1 2 1 
 4: 1 3 3 1 
 5: 1 4 6 4 1 
 6: 1 5 10 10 5 1 
 7: 1 6 15 20 15 6 1 
 8: 1 7 21 35 35 21 7 1 
 9: 1 8 28 56 70 56 28 8 1 
 10: 1 9 36 84 126 126 84 36 9 1 

这是我的 Pascal 类代码:

 public class Pascal
 {
   public static int[] triangle(int n) 
   {
   int [][] pt = new int[n+1][];

     for (int i = 0; i < n; i++) 
     {
     pt[i] = new int[i + 1];
     pt[i][0] = 1;//sets the position to 1
     pt[i][i] = 1;

      for (int j = 1; j < pt[i].length - 1; j++)
      {
       pt[i][j] = pt[i-1][j-1] + pt[i-1][j];
      }
 }
  return new int[]{0};
 }
} 

我的输出:

 1: 0 
 1: 10 
 1: 20 
 1: 1 
 1: 0 
 1: 0 

【问题讨论】:

  • 你的 pascal.triangle 方法总是返回一个空数组??
  • 好吧,我不知道它是否为空,因为它返回的数组包含不应该返回的奇怪数字。

标签: java arrays pascals-triangle


【解决方案1】:

只需 return pt[n-1]; 而不是模板中的新空数组(您应该删除该行)。

有了它,它对我有用,你的算法是正确的。

【讨论】:

  • 1: 0 1: 0 1: 1 1: 1 1: 1 它不起作用,这是我的输出。
  • 我复制粘贴了你的 2 个类,做了我指出的替换,另一个在 Main 中初始化 int n = 10,运行它,得到了预期的输出。
  • 我将主类中的代码修复为int n = args.length == 10 ? Integer.parseInt(args[0]) : 10;,现在它可以工作了!谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-09
  • 2013-06-20
  • 1970-01-01
  • 2014-01-23
  • 2013-08-06
相关资源
最近更新 更多